In the project, I encountered the need to convert a number similar to '450000' into the format used for accounting, '450,000.00'. When there are not enough two digits after separating the thousandth place and the decimal point, it will be automatically filled in. Several types have been recorded. Method of implementation
ps: If you do not consider the decimal point, the fastest way is:
"12345678".replace(/[0-9]+?(?=(?:( [0-9]{3}))+$)/g,function(a){return a+','}); //Output 12 345 678
1. Implement it in a loop
function formatNum(str){ var newStr = ""; var count = 0; if(str.indexOf(".")==-1){ for(var i=str.length-1;i>=0;i--){ if(count % 3 == 0 && count != 0){ newStr = str.charAt(i) + "," + newStr; }else{ newStr = str.charAt(i) + newStr; } count++; } str = newStr + ".00"; //自动补小数点后两位 console.log(str) } else { for(var i = str.indexOf(".")-1;i>=0;i--){ if(count % 3 == 0 && count != 0){ newStr = str.charAt(i) + "," + newStr; //碰到3的倍数则加上“,”号 }else{ newStr = str.charAt(i) + newStr; //逐个字符相接起来 } count++; } str = newStr + (str + "00").substr((str + "00").indexOf("."),3); console.log(str) } } formatNum('13213.24'); //输出13,213.34 formatNum('132134.2'); //输出132,134.20 formatNum('132134'); //输出132,134.00 formatNum('132134.236'); //输出132,134.236
2. Use regular rules (the disadvantage is that you still have to judge the number of digits after the decimal point yourself. If you have a smarter regular rule, please inform me~)
function regexNum(str){ var regex = /(\d)(?=(\d\d\d)+(?!\d))/g; if(str.indexOf(".") == -1){ str= str.replace(regex,',') + '.00'; console.log(str) }else{ var newStr = str.split('.'); var str_2 = newStr[0].replace(regex,','); if(newStr[1].length <= 1){ //小数点后只有一位时 str_2 = str_2 + '.' + newStr[1] +'0'; console.log(str_2) }else if(newStr[1].length > 1){ //小数点后两位以上时 var decimals = newStr[1].substr(0,2); var srt_3 = str_2 + '.' + decimals; console.log(srt_3) } } }; regexNum('23424224'); //输出2,42,224.00 regexNum('23424224.2'); //输出2,42,224.20 regexNum('23424224.22'); //输出2,42,224.22 regexNum('23424224.233'); //输出2,42,224.23
The above is the entire content of this article. To learn more about JavaScript syntax, I hope everyone will support the PHP Chinese website.
For more Javascript to convert numerical values into amount format (separating thousandths and automatically adding decimal points), please pay attention to the PHP Chinese website!