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
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

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!