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

"$ 2,500.00"

我该怎么做?


当前回答

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat示例:使用区域设置

此示例显示了本地化数字格式的一些变体。为了获得应用程序用户界面中使用的语言的格式,请确保使用locales参数指定该语言(可能还有一些回退语言):

变量编号=12346.789;//德语使用逗号作为小数分隔符,句点表示千console.log(新Intl.NumberFormat('de-de').format(数字));//→123.456,789//大多数阿拉伯语国家的阿拉伯语使用真正的阿拉伯数字console.log(新Intl.NumberFormat('ar-EG').format(数字));//→١٢٣٤٥٦٫٧٨٩//印度使用数千/十万/千个分隔符console.log(新Intl.NumberFormat('en-IN').format(数字));

其他回答

使用regexp的更快方法:

Number.prototype.toMonetaryString = function() {
  var n = this.toFixed(2), m;
  //var = this.toFixed(2).replace(/\./, ','); For comma separator
  // with a space for thousands separator
  while ((m = n.replace(/(\d)(\d\d\d)\b/g, '$1 $2')) != n)
      n = m;
  return m;
}

String.prototype.fromMonetaryToNumber = function(s) {
  return this.replace(/[^\d-]+/g, '')/100;
}

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>

这里是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) : '');
});

数字(值).to固定(2).replace(/(\d)(?=(\d{3})+(?!\d))/g,“$1,”)