Javascript将数值转换为金额格式(分隔千分位和自动增加小数点)
在项目里碰到需要把类似'450000'的数字转换为会计记账所用的格式,'450,000.00',分隔千分位和小数点后不够两位数时自动补齐,已下记录几种实现的方式
ps:如果不考虑后面的小数点,最快捷的方法:
"12345678".replace(/[0-9]+?(?=(?:([0-9]{3}))+$)/g,function(a){returna+','});//输出12345678
1.用循环的方式实现
functionformatNum(str){
varnewStr="";
varcount=0;
if(str.indexOf(".")==-1){
for(vari=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(vari=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.使用正则(比较不足的是还是得自己去判断小数点后面的位数,有更智能的正则请通知我~)
functionregexNum(str){
varregex=/(\d)(?=(\d\d\d)+(?!\d))/g;
if(str.indexOf(".")==-1){
str=str.replace(regex,',')+'.00';
console.log(str)
}else{
varnewStr=str.split('.');
varstr_2=newStr[0].replace(regex,',');
if(newStr[1].length<=1){
//小数点后只有一位时
str_2=str_2+'.'+newStr[1]+'0';
console.log(str_2)
}elseif(newStr[1].length>1){
//小数点后两位以上时
vardecimals=newStr[1].substr(0,2);
varsrt_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
以上就是本文的全部内容,了解更多JavaScript的语法,大家可以查看:《JavaScript参考教程》、《JavaScript代码风格指南》,也希望大家多多支持毛票票。