【问题标题】:Format number to dollar将数字格式化为美元
【发布时间】:2016-09-09 21:06:21
【问题描述】:

我有一个数字 5850,我需要将其格式化为美元。

示例 1:

5850 => 58.50 美元

示例 2:

9280 => 92.80 美元

我正在使用以下功能:

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
    var n = this,
        decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
        decSeparator = decSeparator == undefined ? "." : decSeparator,
        thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

上面的函数给了我$5,850.00。

【问题讨论】:

  • 你最好只使用字符串操作,因为无论如何你都是以字符串为目标的。将 5850 转换为字符串,去掉最后两个字符(成为“美分”),然后在剩下的部分插入逗号。将两部分结合起来,完成。

标签: javascript format currency


【解决方案1】:

您仍然可以使用相同的方法,只需稍微调整一下,如下所示:

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
    var n = this,
        decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
        decSeparator = decSeparator == undefined ? "." : decSeparator,
        thouSeparator = '',
        thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

【讨论】:

    【解决方案2】:

    我认为使用可以为您处理它的库会更容易。我使用 currencyFormatter.js (https://osrec.github.io/currencyFormatter.js/) - 试一试。适用于所有浏览器并且非常轻量级。它还会为您添加货币符号,并可以根据指定的语言环境进行格式化:

    OSREC.CurrencyFormatter.format(2534234, { currency: 'INR' }); 
    // Returns ₹ 25,34,234.00
    
    OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR' }); 
    // Returns 2.534.234,00 €
    
    OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR', locale: 'fr' }); 
    // Returns 2 534 234,00 €
    

    【讨论】:

      【解决方案3】:

      如果您不太关心超过 4 位的数字,您可以使用类似

      function dollars(n) {
        return (n+"").replace(/(\d{0,2})(\d{2}).*/, "$$$1.$2")
      }
      

      【讨论】:

        猜你喜欢
        • 2010-09-22
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 2019-08-06
        • 1970-01-01
        • 2020-01-25
        相关资源
        最近更新 更多