首页 > 其他分享 >金额格式化

金额格式化

时间:2023-01-29 17:14:11浏览次数:39  
标签:格式化 sep point 金额 number prec const dec

参数:

  • {number} number:要格式化的数字
  • {number} decimals:保留几位小数
  • {string} dec_point:小数点符号
  • {string} thousands_sep:千分位符号
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  const n = !isFinite(+number) ? 0 : +number
  const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
  const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
  const dec = typeof dec_point === 'undefined' ? '.' : dec_point
  let s = ''
  const toFixedFix = function(n, prec) {
    const k = Math.pow(10, prec)
    return '' + Math.ceil(n * k) / k
  }
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  const re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}

示例:

moneyFormat(10000000) // 10,000,000.00
moneyFormat(10000000, 3, '.', '-') // 10-000-000.000

 

标签:格式化,sep,point,金额,number,prec,const,dec
From: https://www.cnblogs.com/Jishuyang/p/17073200.html

相关文章

  • 【Python基础学习】7.文件和数据格式化
    主要参考来源:慕课嵩天老师的“Python语言程序设计”[https://www.icourse163.org/course/BIT-268001?tid=1468130447]格式化包括字符串格式化和数据格式化字符串格式化:......
  • VS Code保存后自动格式化Vue代码
      在VSCode里面编辑Vue代码,通常我们会安装插件Vetur,本次介绍的格式化代码也依赖于Vetur插件。具体见一下步骤注:VSCode版本为1.74.3   1.安装插件Vetur ......
  • vc下的时间格式化
    formattingcodesforstrftimearelistedbelow:%aAbbreviatedweekdayname%AFullweekdayname%b......
  • 字符串格式化、字符串补0
    不够6位用0在左边补0Longcount=getCountByPredicate(booleanExpression);returnString.format("%06d",count); ......
  • 08_字符串扩展_3.1_字符串格式化%
    """_*_coding:utf-8_*_@Time:2023/1/2220:45@Author:软柠柠吖@Description:字符串格式化%我们会发现,这个拼接字符串也不好用啊①变......
  • 08_字符串扩展_4_格式化的精度控制
    """_*_coding:utf-8_*_@Time:2023/1/2221:01@Author:软柠柠吖@Description:格式化的精度控制我们可以使用辅助符号"m.n"来控制数据的宽度和......
  • 08_字符串扩展_3.3_表达式的格式化
    """_*_coding:utf-8_*_@Time:2023/1/2221:19@Author:软柠柠吖@Description:表达式的格式化表达式:一条具有明确执行结果的代码语句使用场......
  • 在Visual Studio2022使用AStyle格式化代码
    前言 最近用VS2022写C++代码,虽然可以直接设置自己的代码风格,但效果并不那么如意,甚至在格式化后的代码还有下面这样的     于是我又试着使用了clang-forma......
  • python 字符串格式化
    一、%1#%d%f%s2#%ndn为位置的数量,n>0正数居右,n<0正数居左3#%f默认保留小数点后6位,%.nf,n为保留小数点后几位4print("%s有%2d个老婆,每个老婆要给%f两"%......
  • Swift-数字字符串格式化
    之前看到一段代码:letstr="lazy"String(format:"%@boy",arguments:[str])    没理解意思,后来在网上查了查这属于【字符串格式化】,随后我做了归总,有需要的......