【问题标题】:Javascript decimal calculations [duplicate]Javascript十进制计算[重复]
【发布时间】:2015-03-10 21:42:53
【问题描述】:

您好,我有 3 个值,格式为 1000、2000、200。 我正在使用此函数将它们转换为以下格式

 function formatNumber(number)
    {
        number = number.toFixed(2) + '';
        x = number.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? ',' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + '.' + '$2');
        }
        return x1 + x2;
    }

1.000,00 2.000,00 和 200,00

我如何计算它们,结果将是 3.200,00?

我在每个语句中计算它们,因为我的应用程序中可以生成更多字段。

谢谢。 任何帮助将不胜感激。

【问题讨论】:

  • 所以我不太确定你的问题,但为什么不添加所有值然后格式化结果?
  • 重复使用逗号作为千位分隔符,只需更改此问题的字符即可。

标签: javascript math calculator currency


【解决方案1】:

这是我不久前从另一篇 StackOverflow 帖子改编的函数。有关详细信息,请参阅源代码中的链接。

/* 
http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
decimal_sep: character used as deciaml separtor, it defaults to '.' when omitted
thousands_sep: char used as thousands separator, it defaults to ',' when omitted
*/
Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep) { 
   var n = this,
   c = isNaN(decimals) ? 2 : Math.abs(decimals), //if decimal is zero we must take it, it means user does not want to show any decimal
   d = decimal_sep || '.', //if no decimal separator is passed we use the dot as default decimal separator (we MUST use a decimal separator)

   /*
   according to [http://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
   the fastest way to check for not defined parameter is to use typeof value === 'undefined' 
   rather than doing value === undefined.
   */   
   t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, //if you don't want to use a thousands separator you can pass empty string as thousands_sep value

   sign = (n < 0) ? '-' : '',

   //extracting the absolute value of the integer part of the number and converting to string
   i = parseInt(n = Math.abs(n).toFixed(c)) + '', 

   j = ((j = i.length) > 3) ? j % 3 : 0; 
   return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); 
}

你可以这样使用它

var num = 1000 + 2000 + 200;
num.toMoney(2, ',', '.'); // => 3.200,00

【讨论】:

  • 是的,我现在知道了。有没有机会用类似的功能将数字 1.000,00 取消格式化为第一个值 1000 ?
猜你喜欢
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
相关资源
最近更新 更多