实现千位分隔符
文章链接
const a = 12345678910
const b = 123456.789
console.log(a.toLocaleString()) // 12,345,678,910
console.log(b.toLocaleString()) // 123,456.789
function numFormat(num, format = '_') {
// 小于一千直接返回
if (num < 1000) {
return num
}
let str = num + ''
const strList = str.split('.')
const strMin = strList[1] ? `.${strList[1]}` : ''
// 只针对整数部分
if (strMin) {
str = strList[0]
}
// 提示:从后面插入,不会影响前面的索引
// 12345678910
// 12345678_910
// 12345_678_910
// 12_345_678_910
let flag = 0
const list = Array.from(str)
for (let i = list.length - 1; i > 0; i--) {
flag++
if (flag === 3) {
list.splice(i, 0, format)
flag = 0
}
}
return list.join('') + strMin
}
console.log(numFormat(a, '__'))
console.log(numFormat(b, '__'))
console.log(numFormat(999))
console.log(numFormat(1000))
console.log(numFormat(1234))
console.log(numFormat(12345))
console.log(numFormat(123456))
console.log(numFormat(1234567))
console.log(numFormat(12345678))
console.log(numFormat(123456789))
console.log(numFormat(1234567890.1234))