您好,欢迎来到99网。
搜索
您的当前位置:首页Javascript将数值转换为金额格式(分隔千分位和自动增加小数点)

Javascript将数值转换为金额格式(分隔千分位和自动增加小数点)

来源:99网


在项目里碰到需要把类似'450000'的数字转换为会计记账所用的格式,'450,000.00',分隔千分位和小数点后不够两位数时自动补齐,已下记录几种实现的方式

ps:如果不考虑后面的小数点,最快捷的方法:

"12345678".replace(/[0-9]+?(?=(?:([0-9]{3}))+$)/g,function(a){return a+','}); //输出 12 345 678

1.用循环的方式实现

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.使用正则(比较不足的是还是得自己去判断小数点后面的位数,有更智能的正则请通知我~)

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

Copyright © 2019- 99spj.com 版权所有 湘ICP备2022005869号-5

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务