问题描述
我想使用 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/