How to format numbers using JavaScript?

19,246

Solution 1

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/

Solution 2

I know this solution using NumberFormat but it is necessary to convert the values to string. https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/NumberFormat

// Remove commas
number = "10,000.00".replace(/,/g, '');

// Create a NumberFormat type object
var formatter = new Intl.NumberFormat('de-DE', {
    minimumFractionDigits: 2
}); 

// Apply format
console.log(formatter.format(number));

output:10.000,00

Solution 3

Javascript doesn't provide this functionality itself, but there are a number of third-party functions around which can do what you want.

Note, whichever method you use, you should be careful to only use the resulting string for display purposes -- it won't be a valid number value in Javascript after you've converted the decimal point to a comma.

The quickest solution I can offer is to use the number_format() function written by the phpJS people. They've implemented Javascript versions of a load of commonly-used PHP functions, including number_format(), and this function will do exactly what you want.

See the link here: http://phpjs.org/functions/number_format

I wouldn't bother about taking the whole phpJS library (a lot of it is of questionable value anyway), but just grab the 20-odd line function shown on the page linked above and paste it into your app.

If you want a more flexible solution, there are a number of JS functions around which simulate the printf() function from C. There is already a good question on SO covers this. See here: JavaScript equivalent to printf/string.format

Hope that helps.

Share:
19,246
Kanak Vaghela
Author by

Kanak Vaghela

Updated on June 12, 2022

Comments

  • Kanak Vaghela
    Kanak Vaghela almost 2 years

    I want to format number using javascript as below:

    10.00=10,00 
    1,000.00=1.000,00
    
    • Shadow The Kid Wizard
      Shadow The Kid Wizard about 13 years
    • Pav
      Pav about 13 years
    • Kanak Vaghela
      Kanak Vaghela about 13 years
      @Shadow Wizard : No this is not same. I could not get the result for 1,50,000.00 as 1.50.000,00 using that script..
    • Shadow The Kid Wizard
      Shadow The Kid Wizard about 13 years
      So you might have to write your own "format" function using string manipulation.
  • Maksym Kozlenko
    Maksym Kozlenko over 12 years
    I'm voting for this solution, since it supports proper localization. Some of us are using decimal comma instead of dot :-)
  • Patrick Klug
    Patrick Klug about 11 years
    +1 - just a warning: needs to be fixed to deal properly with negative numbers. currently -100 returns -,100.00 for example.
  • Patrick Klug
    Patrick Klug about 11 years
    just to be clear. to see the issue you'll need to call (-100).toLocaleString()
  • Andy E
    Andy E about 11 years
    @PatrickKlug: Thanks for pointing it out, I didn't originally consider negatives and didn't test them. I've fixed it now :-)
  • bancer
    bancer over 7 years
    What about converting the localized number back?
  • Achim Koellner
    Achim Koellner over 5 years
    if you're planning to run unittests in node.js you will need to load the intl package