我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:

"$ 2,500.00"

我该怎么做?


当前回答

toLocaleString很好,但它不适用于所有浏览器。我通常使用currencyFormatter.js(https://osrec.github.io/currencyFormatter.js/). 它非常轻量级,包含所有现成的货币和语言环境定义。它还擅长格式化格式异常的货币,如INR(以10万卢比、10万卢比等为单位分组)。此外,没有任何依赖关系!

OSREC.CurrencyFormatter.format(2534234,{currency:'INR'});//退换商品₹ 25,34,234.00

OSREC.CurrencyFormatter.format(2534234,{currency:'EUR'});//退货2.534.234,00欧元

OSREC.CurrencyFormatter.format(2534234,{currency:'EUR',locale:'fr'});//退货2 534 234,00欧元

其他回答

数字.原型.固定

此解决方案与每个主要浏览器都兼容:

  const profits = 2489.8237;

  profits.toFixed(3) // Returns 2489.824 (rounds up)
  profits.toFixed(2) // Returns 2489.82
  profits.toFixed(7) // Returns 2489.8237000 (pads the decimals)

您只需添加货币符号(例如“$”+利润.toFixed(2)),即可获得美元金额。

自定义函数

如果需要在每个数字之间使用,则可以使用此函数:

函数格式Money(number,decPlaces,decSep,thouSep){decPlaces=isNaN(decPlaces=数学.abs(decPlaces))?2:decPlaces,decSep=decSep的类型==“未定义”?“.”:12月9日;thouSep=thouSep==“未定义”的类型?“,”:thouSep;var符号=数字<0?"-" : "";var i=字符串(parseInt(number=Math.abs(number(number)||0).toFixed(decPlaces)));变量j=(j=i.length)>3?j%3:0;返回标志+(j?i.substr(0,j)+thouSep:“”)+i.substr(j).replace(/(\decSep{3})(?=\decSep)/g,“$1”+thouSep)+(decPlaces?decSep+Math.abs(数字-i).toFixed(decPlace).slice(2):“”);}document.getElementById(“b”).addEventListener(“单击”,event=>{document.getElementById(“x”).innerText=“结果为:”+formatMoney(document.getElement ById(”d“).value);});<label>插入您的金额:<input id=“d”type=“text”placeholder=“Cash amount”/></label><br/><button id=“b”>获取输出</button><p id=“x”>(按下按钮获取输出)</p>

这样使用:

(123456789.12345).formatMoney(2, ".", ",");

如果你总是使用“.”和',',您可以将它们从方法调用中删除,方法将为您默认它们。

(123456789.12345).formatMoney(2);

如果您的文化中有两个符号翻转(即,欧洲人),并且您希望使用默认值,只需在formatMoney方法中粘贴以下两行:

    d = d == undefined ? "," : d,
    t = t == undefined ? "." : t,

自定义功能(ES6)

如果您可以使用现代ECMAScript语法(即,通过Babel),则可以使用更简单的函数:

函数formatMoney(amount,decimalCount=2,decimal=“.”,千=“,”){尝试{decimalCount=数学.abs(decimalCount);decimalCount=isNaN(decimalCount)?2:小数计数;常量负符号=金额<0?"-" : "";让i=parseInt(amount=Math.abs(Number(amount)||0).toFixed(decimalCount)).toString();设j=(i.length>3)?i.长度%3:0;回来否定符号+(j?i.substr(0,j)+千:“”)+i.substr(j).replace(/(\d{3})(?=\d)/g,“$1”+千)+(decimalCount?decimal+Math.abs(amount-i).toFixed(decimalCount).slice(2):“”);}捕获(e){控制台日志(e)}};document.getElementById(“b”).addEventListener(“单击”,event=>{document.getElementById(“x”).innerText=“结果为:”+formatMoney(document.getElement ById(”d“).value);});<label>插入您的金额:<input id=“d”type=“text”placeholder=“Cash amount”/></label><br/><button id=“b”>获取输出</button><p id=“x”>(按下按钮获取输出)</p>

请尝试以下代码

"250000".replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');

答案:250000

这里是XMLilley提供的代码的mootools1.2实现。。。

Number.implement('format', function(decPlaces, thouSeparator, decSeparator){
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
decSeparator = decSeparator === undefined ? '.' : decSeparator;
thouSeparator = thouSeparator === undefined ? ',' : thouSeparator;

var num = this,
    sign = num < 0 ? '-' : '',
    i = parseInt(num = Math.abs(+num || 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(num - i).toFixed(decPlaces).slice(2) : '');
});

JavaScript中没有“formatNumber”的等价物。你可以自己写,也可以找一个已经这样做的库。

下面是Patrick Desjardins(别名Daok)代码,添加了一些注释和一些小改动:

/*
decimal_sep: character used as decimal separator, 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 the 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 [https://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) : '');
}

这里有一些测试:

// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert(123456789.67392.toMoney() + '\n' + 123456789.67392.toMoney(3) + '\n' + 123456789.67392.toMoney(0) + '\n' + (123456).toMoney() + '\n' + (123456).toMoney(0) + '\n' + 89.67392.toMoney() + '\n' + (89).toMoney());

// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert((-123456789.67392).toMoney() + '\n' + (-123456789.67392).toMoney(-3));

次要变化包括:

移动了一点Math.abs(小数),只有当不是NaN时才能执行。decimal_sep不能再是空字符串(必须使用某种十进制分隔符)我们使用typeof thousand_sep===“undefined”,如How best to determine if a argument is not send to JavaScript function中所建议的不需要(+n||0),因为这是Number对象

JSFiddle公司