- toLocaleString
// JS 自带的 toLocaleString
function formatNumber(num) {
return Number(num).toLocaleString()
}
console.log(formatNumber(123456789.123)) // 123,456,789.123
- 正则
// 正则表达式
function formatNumber(num) {
return num.toString().replace(/\d+/, function (n) {
return n.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
})
}
console.log(formatNumber(123456789.123)) // 123,456,789.123
- 递归
// 字符串递归方法
function formatNumber(num, chart=',', length=3) {
let result = ''
let nums = num.toString().split('.')
let int = nums[0]
let decmial = nums[1] ? '.' + nums[1] : ''
let index = 0
for (let n = int.length - 1; n >= 0; n--) {
index ++
result = int[n] + result
if (index % length === 0 && n !== 0) { result = chart + result }
}
return result + decmial
}
console.log(formatNumber(123456789.123)) // 123,456,789.123
- slice 截取分割
// slice 截取分割
function formatNumber(num, char=',', length=3) {
let result = ''
let nums = num.toString().split('.')
let int = nums[0];
let decmial = nums[1] ? '.' + nums[1] : ''
while (int.length > length) {
result = char + int.slice(-length) + result
int = int.slice(0, int.length - length)
}
if (int) { result = int + result }
return result + decmial
}
console.log(formatNumber(123456789.123)) // 123,456,789.123