DEV Community

M. Andrew Darts
M. Andrew Darts

Posted on

2 1

Intl Formatting Numbers in Javascript

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
Enter fullscreen mode Exit fullscreen mode

Need support for Spanish?

Intl.NumberFormat('es').format(40000); // 40.000
Enter fullscreen mode Exit fullscreen mode

Currency is a tricky one.

Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD"
}).format(40000); // $40,000.00
Enter fullscreen mode Exit fullscreen mode

Currency Again, Spanish?

Intl.NumberFormat("es", {
  style: "currency",
  currency: "USD"
}).format(40000); // 40.000,00 US$
Enter fullscreen mode Exit fullscreen mode

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more