给一个数字添加上千位分隔符
千位分隔符就是数字中的逗号。依西方的习惯,人们在数字中加进一个符号,以免因数字位数太多而难以看出它的值。所以人们在数字中,每隔三位数加进一个逗号,也就是千位分隔符,以便更加容易认出数值。
1000
--->1,000
1000000
--->1,000,000
100000000
--->100,000,000
常规思路
- 将数字转为字符串,将小数部分与整数部分分离
- 整数部分分隔为数组,并且反转
- 反转后的数组每隔3位添加
,
- 添加完成后,再反转回来,拼接小数部分,完成格式化
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, ',')