1, toLocaleString ()
Var num = 123456789.65478; var result=num.toLocaleString(); console.log(result); / / 123.456.789.65478Copy the code
2. Re (integer only)
var num=123456789; <! --var reg=/(\d)(? = (? :\d{3}))+$/g; --> var reg=/(\d)(? =(\d{3})+$)/g; var result=num.replace(reg,"The $1,");
console.log(result);
Copy the code
? : Ignored during replacement
Packaging function
1, js
functionNumFormat (num){// Convert numbers to strings and split integer and decimal parts numArr=num.toString().split(".");
letnewArr=[]; Var numStr=numArr[0].split(' ');
for(var i=0; i<numStr.length; i++){if((i+1)%3===0){
newArr.unshift(","); } newArr.unshift(numStr[i]); } // If there are decimal parts, join them together after the operation is completeif(numArr[1]){
newArr=newArr.join("").concat("."+numArr[1]);
}else{
newArr=newArr.join("");
}
console.log(newArr)
}
Copy the code
2, toLocaleString ()
function numFormat(num){
let result=num.toLocaleString();
console.log(result);
}
Copy the code
3, regular
function numFormat(num){
let result=num.toString().indexOf(".")! = = 1? num.toLocaleString(): num.replace(/(\d)(? =(\d{3})+$)/g,"The $1,")
console.log(result);
}
numFormat(1234568.23); // 1,234,568.23
Copy the code