International digital format

Formatting numbers on the client side is an important task, especially when you consider how many raw APIs are used these days. It is also important to ensure that these numbers make sense to users no matter where they are, especially if you are an e-commerce website.

Writing internationalized code may be a nightmare, but fortunately JavaScript provides us with Intl.NumberFormat, An API used to internationalize numbers into currencies, etc. Let’s see!

Some examples 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" }

If the number you want to display is in a standard format, please don’t bother to write your own client-side number format function-take advantage of the amazing API provided by your browser!

Leave a Reply

Your email address will not be published. Required fields are marked *