【问题标题】:JavaScript - easy way to format something to currency w/out decimalsJavaScript - 将某些东西格式化为没有小数的货币的简单方法
【发布时间】:2016-05-27 23:54:40
【问题描述】:

我一直在尝试想出一种方法,而不使用某人的插件将带小数的数字格式化为不带小数的货币。到目前为止,我发现以下是最简单的方法:

yourVar.toLocaleString("en", { style: 'currency', currency: 'USD' }).split('.')[0]

示例:

before:446882086.00

after:$446,882,086

【问题讨论】:

    标签: javascript


    【解决方案1】:

    在这个问题的帮助下:Add commas or spaces to group every three digits

    我已经创建了这个函数:

    function convertString(currency, input) {
      var thisInt = Math.round(input); //this removes numbers after decimal   
      var thisOutputValue = currency + commafy(thisInt); //add currency symbol and commas
    
      return thisOutputValue;
    }
    
    
    function commafy(num) {
      var str = num.toString().split('.');
      if (str[0].length >= 5) {
        str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
      }
      if (str[1] && str[1].length >= 5) {
        str[1] = str[1].replace(/(\d{3})/g, '$1 ');
      }
      return str.join('.');
    }    
    
    var changeIntToCurrencyString = convertString('$', 435345.00) //change numbers into dollars
    
    console.log(changeIntToCurrencyString )
    

    以上代码将整数435345.00转换为美元货币字符串:$435,345。它应该适用于所有其他整数值:)

    小提琴:https://jsfiddle.net/thatOneGuy/zL817x5a/3/

    function convertString(currency, input) {
      var thisInt = Math.round(input); //this removes numbers after decimal   
      var thisOutputValue = currency + commafy(thisInt); //add currency symbol and commas
    
      return thisOutputValue;
    }
    
    
    function commafy(num) {
      var str = num.toString().split('.');
      if (str[0].length >= 5) {
        str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
      }
      if (str[1] && str[1].length >= 5) {
        str[1] = str[1].replace(/(\d{3})/g, '$1 ');
      }
      return str.join('.');
    }
    
    var tryoutint = 435345.00;
    var changeIntToCurrencyString = convertString('$', tryoutint) //change numbers into dollars
    
    console.log(changeIntToCurrencyString)
    alert(tryoutint + ' : ' + changeIntToCurrencyString)

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 2012-06-26
      • 2019-06-24
      • 2012-11-09
      相关资源
      最近更新 更多