Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

localization - How to format numbers using JavaScript?

I want to format number using javascript as below:

10.00=10,00 
1,000.00=1.000,00
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Every browser supports Number.prototype.toLocaleString(), a method intended to return a localized string from a number. However, the specification defines it as follows:

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 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+) formats the number with a thousands separator and decimal places but only if applicable.

Opera, Chrome & Safari output the same as toString() -- no thousands separator, decimal place only if required.

Solution

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.

Working demo: http://jsfiddle.net/R4DKn/49/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...