我想使用 javascript 格式化数字,如下所示:
10.00=10,00
1,000.00=1.000,00
最佳答案
每个浏览器都支持 Number.prototype.toLocaleString()
,这是一种旨在从数字返回本地化字符串的方法。但是,规范将其定义如下:
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment's current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as
toString
.
依赖于实现意味着结果的外观取决于 vendor ,并导致互操作性问题。
Internet Explorer(IE 5.5 到 IE 9)最接近您想要的,并以货币样式格式化数字 - 千位分隔符并固定在小数点后 2 位。
Firefox (2+) 使用千位分隔符和小数位格式化数字,但前提是适用。
Opera、Chrome 和 Safari 输出与 toString()
相同——没有千位分隔符,仅在需要时保留小数位。
解决方案
我想出了以下代码(基于 an old answer of mine )来尝试规范化结果,使其像 Internet Explorer 的方法一样工作:
(function (old) {
var dec = 0.12 .toLocaleString().charAt(1),
tho = dec === "." ? "," : ".";
if (1000 .toLocaleString() !== "1,000.00") {
Number.prototype.toLocaleString = function () {
var neg = this < 0,
f = this.toFixed(2).slice(+neg);
return (neg ? "-" : "")
+ f.slice(0,-3).replace(/(?=(?!^)(?:\d{3})+(?!\d))/g, tho)
+ dec + f.slice(-2);
}
}
})(Number.prototype.toLocaleString);
这将使用浏览器的内置本地化(如果可用),同时在其他情况下优雅地降级为浏览器的默认语言环境。
关于javascript - 如何使用 JavaScript 格式化数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5882994/