跳到主要内容

1 篇博文 含有标签「format」

查看所有标签

· 阅读需 2 分钟

给一个数字添加上千位分隔符

千位分隔符就是数字中的逗号。依西方的习惯,人们在数字中加进一个符号,以免因数字位数太多而难以看出它的值。所以人们在数字中,每隔三位数加进一个逗号,也就是千位分隔符,以便更加容易认出数值。

  • 1000 ---> 1,000
  • 1000000 ---> 1,000,000
  • 100000000 ---> 100,000,000

常规思路

  1. 将数字转为字符串,将小数部分与整数部分分离
  2. 整数部分分隔为数组,并且反转
  3. 反转后的数组每隔3位添加 ,
  4. 添加完成后,再反转回来,拼接小数部分,完成格式化
function formatNumber(number) {
const [integer, decimal] = number.toString().split('.')
const integerArr = integer.split('')
integerArr.reverse()
const result = []
for (let i = 0; i < integerArr.length; i++){
if (i % 3 === 0 && i !== 0) {
result.push(',')
}
result.push(integerArr[i])
}
result.reverse()
if (decimal) {
return `${result.join('')}.${decimal}`
}
return result.join('')
}

Number.prototype.toLocaleString()

返回数字在特定语言环境下表示的字符串

Number(1000000).toLocaleString() // '1,000,000'

Intl.NumberFormat()

new Intl.NumberFormat().format(10000000) // '10,000,000'

正则前瞻运算符

const r = str.replace(/\B(?=(\d{3})+$)/g, ',')