Formatting numbers is key to many applications. This may seem like a small task to an experienced developer, but the thought of having to write these for every application I start is disheartening. Well, anyways, enough with my rant. Let's look for a library to knock this out so we can move on. We need a solution that handles percentages, currency, and many languages. Hmm? What if there was an API in the browser?
Using Intl.NumberFormat
The Intl.NumberFormat
API can handle percentages, decimals, currencies and locale. Let's check it out.
Adding commas where needed
Intl.NumberFormat().format(40000); // 40,000
Need support for Spanish?
Intl.NumberFormat('es').format(40000); // 40.000
Currency is a tricky one.
Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD"
}).format(40000); // $40,000.00
Currency Again, Spanish?
Intl.NumberFormat("es", {
style: "currency",
currency: "USD"
}).format(40000); // 40.000,00 US$
Other Examples
I'll keep this short and sweet. I encourage you, next time you reach for a library to solve a problem, look to the platform first!
References
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
Browser Support: https://caniuse.com/#search=NumberFormat
Top comments (0)