let num = 12345.2249
console.log(num.toLocaleString()); // 12,345.225
- 单独抽离整数部分并翻转,使用除余手动在相应位置添加逗号,最后与小数部分进行拼接
let num = 12345.2249
let intNum = num.toString().split('.')
let arr = []
for (let i = intNum[0].length - 1; i >= 0; i--) {
arr.push(intNum[0][i])
if((i+1) % 3 == 0) arr.push(',')
}
console.log(arr.reverse().join('') + '.' + intNum[1]) // 12,345.2249
- 单独抽离整数部分,直接使用slice截取后三位与逗号拼接
let num = 12345.2249
let intNum = num.toString().split('.')
let newStr = ''
while(intNum[0].length > 3) {
newStr = ',' + intNum[0].slice(-3) + newStr
intNum[0] = intNum[0].slice(0, intNum[0].length - 3)
}
newStr = intNum[0] + newStr
console.log(newStr + '.' + intNum[1]); // 12,345.2249