如何使用 JavaScript 格式化数字?
我想使用 javascript 格式化数字,如下所示:
I want to format number using javascript as below:
10.00=10,00
1,000.00=1.000,00
推荐答案
每个浏览器都支持 Number.prototype.toLocaleString()
,这是一种旨在从数字返回本地化字符串的方法.但是,规范将其定义如下:
Every browser supports Number.prototype.toLocaleString()
, a method intended to return a localized string from a number. However, the specification defines it as follows:
生成一个字符串值,该值表示根据宿主环境当前语言环境的约定格式化的数字值.此函数依赖于实现,允许但不鼓励它返回与 toString
相同的内容.
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
.
依赖于实现意味着由供应商决定结果的外观,并导致互操作性问题.
Implementation-dependant means that it's up to the vendor how the result will look, and results in interoperability issues.
Internet Explorer(IE 5.5 到 IE 9)最接近您想要的格式,并以货币样式格式化数字 - 千位分隔符并固定为小数点后 2 位.
Internet Explorer (IE 5.5 to IE 9) comes closest to what you want and formats the number in a currency style - thousands separator and fixed at 2 decimal places.
Firefox (2+) 使用千位分隔符和小数位格式化数字,但仅在适用的情况下.
Firefox (2+) formats the number with a thousands separator and decimal places but only if applicable.
Opera、Chrome 和Safari 输出与 toString()
相同 -- 没有千位分隔符,仅在需要时使用小数位.
Opera, Chrome & Safari output the same as toString()
-- no thousands separator, decimal place only if required.
我想出了以下代码(基于 我的一个旧答案) 尝试将结果标准化以像 Internet Explorer 的方法一样工作:
I came up with the following code (based on an old answer of mine) to try and normalize the results to work like Internet Explorer's method:
(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);
这将使用浏览器的内置本地化(如果可用),同时在其他情况下优雅地降级为浏览器的默认语言环境.
This will use the browser's built-in localization if it's available, whilst gracefully degrading to the browser's default locale in other cases.
工作演示:http://jsfiddle.net/R4DKn/49/
相关文章