How to Internationalize Numbers with JavaScript

By  on  

Presenting numbers in a readable format takes many forms, from visual charts to simply adding punctuation. Those punctuation, however, are different based on internationalization. Some countries use , for decimal, while others use .. Worried about having to code for all this madness? Don't -- JavaScript provides a method do the hard work for you!

The Number primitive has a toLocaleString method to do the basic formatting for you:

const price = 16601.91;

// Basic decimal format, no providing locale
// Uses locale provided by browser since none defined
price.toLocaleString(); // "16,601.91"

// Provide a specific locale
price.toLocaleString('de-DE'); // "16.601,91"

// Formatting currency is possible
price.toLocaleString('de-DE', { 
  style: 'currency', 
  currency: 'EUR' 
}); // "16.601,91 €"

// You can also use Intl.NumberFormat for formatting
new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'GBP'
}).format(price); // £16,601.91

It's a major relief that JavaScript provides us these type of helpers so that we don't need to rely on bloated third-party libraries. No excuses -- the tool is there!

Recent Features

  • By
    From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...

  • By
    Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today's websites and devices become ever more varied, a plethora of responsive images...

Incredible Demos

Discussion

  1. Simple usage without specifying a locale returns a formatted string in the default locale and with default options.

    const number = 3500;
    
    console.log(new Intl.NumberFormat().format(number));
    // '3,500' if in US English locale
    

    See more options with dashingarts.

  2. Is there any difference in the formatting between

    toLocaleString

    and format using

    new Intl.NumberFormat(...)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!