Intl.NumberFormat

By  on  

Formatting numbers on the client side is an important task, especially when you consider how much raw API usage is in play these days. What's also important is ensuring those numbers are meaningful to users, no matter where they are in the world, especially if you're an eCommerce website.

Writing internationalization code can be a nightmare but luckily JavaScript provides us Intl.NumberFormat, an API for internationalizing numbers as currencies and more. Let's check it out!

Some examples of Intl.NumberFormat include:

new Intl.NumberFormat().format(12345)
// 12,345

new Intl.NumberFormat('en-US', { maximumSignificantDigits: 4}).format(1.2345678)
// 1.235 (Notice the rounding)

new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' }).format(9002.20)
// £9,002.20

new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(9002.20)
// 9.002,20 €

new Intl.NumberFormat().formatToParts(12345.678)
/*
[
   { "type":"integer", "value":"12" },
   { "type":"group", "value":"," },
   { "type":"integer", "value":"345" },
   { "type":"decimal", "value":"." },
   { "type":"fraction", "value":"678" }
]
*/

Don't bother writing your own client side number formatting functions if the numbers you want to present are standard formats -- leverage the amazing APIs the browser provides you!

Recent Features

  • By
    CSS 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • By
    Add Styles to Console Statements

    I was recently checking out Google Plus because they implement some awesome effects.  I opened the console and same the following message: WARNING! Using this console may allow attackers to impersonate you and steal your information using an attack called Self-XSS. Do not enter or paste code that you...

  • By
    Assign Anchor IDs Using MooTools 1.2

    One of my favorite uses of the MooTools JavaScript library is the SmoothScroll plugin. I use it on my website, my employer's website, and on many customer websites. The best part about the plugin is that it's so easy to implement. I recently ran...

Discussion

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