网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 Javascript将数值转换为金额格式(分隔千分位和自动增加小数点)
内容
    在项目里碰到需要把类似'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 © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/16 0:46:10