Javascript converts values to money format (separating thousands and automatically increasing decimal points)
- 2021-06-29 10:04:49
- OfStack
Encountered in the project the need to convert a number like'450000'to the format used for accounting,'450,000.00', auto-completion when not enough two digits after separating thousands and decimal points, several ways of implementation have been recorded
ps: If you don't consider the next decimal point, the quickest way is:
"12345678". replace (/[0-9]+ ?(?=(? ([0-9]{3})+$)/g, function (a){return a+','};//Output 12 345 678
1. Implement in a circular manner
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 complement the last two decimal places
console.log(str)
}
else
{
for(var i = str.indexOf(".")-1;i>=0;i--){
if(count % 3 == 0 && count != 0){
newStr = str.charAt(i) + "," + newStr; // Meet 3 A multiple of , "Number
}else{
newStr = str.charAt(i) + newStr; // Join character by character
}
count++;
}
str = newStr + (str + "00").substr((str + "00").indexOf("."),3);
console.log(str)
}
}
formatNum('13213.24'); // output 13,213.34
formatNum('132134.2'); // output 132,134.20
formatNum('132134'); // output 132,134.00
formatNum('132134.236'); // output 132,134.236
2. Use rules (less or less, you have to decide the number of digits behind the decimal point yourself. 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){
// Only after decimal point 1 Bit time
str_2 = str_2 + '.' + newStr[1] +'0';
console.log(str_2)
}else if(newStr[1].length > 1){
// When two or more decimal places are behind
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.20
regexNum('23424224.22'); // output 2,42,224.22
regexNum('23424224.233'); // output 2,42,224.23