In the project, I encountered a number similar to '450000' needs to be converted into the format used for accounting accounting, '450,000.00', which will automatically fill up if there are not enough two digits after the thousandth and decimal points. Several implementation methods have been recorded.
ps: If you do not consider the following decimal points, the fastest way:
"12345678".replace(/[0-9]+?(?=(?:([0-9]{3}))+$)/g,function(a){return a+','}); //Output 12 345 678
1. Implement 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"; //Automatically fill the two decimal points console.log(str) } else { for(var i = str.indexOf(".")-1;i>=0;i--){ if(count % 3 == 0 && count != 0){ newStr = str.charAt(i) + "," + newStr; //If you encounter a multiple of 3, add the "," sign}else{ newStr = str.charAt(i) + newStr; //Connect one by one} count++; } str = newStr + (str + "00").substr((str + "00").indexOf("."),3); console.log(str) }}formatNum('13213.24'); //Output 13,213.34formatNum('132134.2'); //Output 132,134.20formatNum('132134'); //Output 132,134.00formatNum('132134.236'); //Output 132,134.2362. Use the regularity (Is it necessary to judge the number of digits after the decimal point by yourself? Please notify me if there are smarter rules~)
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){ // When there is only one after the decimal point str_2 = str_2 + '.' + newStr[1] +'0'; console.log(str_2) }else if(newStr[1].length > 1){ //When more than two decimal places are var decimals = newStr[1].substr(0,2); var srt_3 = str_2 + '.' + decimals; console.log(srt_3) } }};regexNum('23424224'); //Output 2,42,224.00 regexNum('23424224.2'); //Output 2,42,224.20regexNum('23424224.22'); //Output 2,42,224.22regexNum('23424224.23'); //Output 2,42,224.23The above is the entire content of this article. For more information about JavaScript, you can check out: "JavaScript Reference Tutorial" and "JavaScript Code Style Guide". I also hope that everyone will support Wulin.com more.