問題描述
我想使用 javascript 格式化數(shù)字,如下所示:
I want to format number using javascript as below:
10.00=10,00
1,000.00=1.000,00
推薦答案
每個瀏覽器都支持 Number.prototype.toLocaleString()
,這是一種旨在從數(shù)字返回本地化字符串的方法.但是,規(guī)范將其定義如下:
Every browser supports Number.prototype.toLocaleString()
, a method intended to return a localized string from a number. However, the specification defines it as follows:
生成一個字符串值,該值表示根據(jù)宿主環(huán)境當前語言環(huán)境的約定格式化的數(shù)字值.此函數(shù)依賴于實現(xiàn),允許但不鼓勵它返回與 toString
相同的內(nèi)容.
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
.
依賴于實現(xiàn)意味著由供應商決定結果的外觀,并導致互操作性問題.
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)最接近您想要的格式,并以貨幣樣式格式化數(shù)字 - 千位分隔符并固定為小數(shù)點后 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+) 使用千位分隔符和小數(shù)位格式化數(shù)字,但僅在適用的情況下.
Firefox (2+) formats the number with a thousands separator and decimal places but only if applicable.
Opera、Chrome 和Safari 輸出與 toString()
相同 -- 沒有千位分隔符,僅在需要時使用小數(shù)位.
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);
這將使用瀏覽器的內(nèi)置本地化(如果可用),同時在其他情況下優(yōu)雅地降級為瀏覽器的默認語言環(huán)境.
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/
這篇關于如何使用 JavaScript 格式化數(shù)字?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!