# JavaScript 千位分隔符

## 方法一

``````  function numFormat(num) {
let newNum = []
let numberArray = number.toString().split(".")
let reverseNumber = numberArray[0].split("").reverse()
for (let i = 0; i < reverseNumber.length; i++) {
if (i % 3 === 0 && i !== 0) {
newNum.push(",")
}
newNum.push(reverseNumber[i])
}
newNum.reverse()
if (numberArray[1]) {
newNum = newNum.join("") + "." + numberArray[1]
} else {
newNum = newNum.join("")
}
return newNum
}
console.log(numFormat(number))

## 方法二

toLocaleString() 方法可把一个 Number 对象转换为本地格式的字符串

``````NumberObject.toLocaleString()

``````const a=1234567894532;
const b=673439.4542;

console.log(a.toLocaleString());  // "1,234,567,894,532"
console.log(b.toLocaleString());  // "673,439.454"  （小数部分四舍五入了, 貌似只能留三位小数）

## 方法三

``````str.replace(regexp|substr, newSubStr|function)

``````function numFormat(num){
var res=num.toString().replace(/\d+/, function(n){ // 先提取整数部分
return n.replace(/(\d)(?=(\d{3})+\$)/g,function(\$1){
return \$1+",";
});
})
return res;
}

var a=1234567894532;
var b=673439.4542;
console.log(numFormat(a)); // "1,234,567,894,532"
console.log(numFormat(b)); // "673,439.4542"