DEV Community

Edwin
Edwin

Posted on • Edited on

3 3

Format numbers in the user's locale using vanilla JS

JavaScript has a built-in language-sensitive number formatting feature, called Intl.NumberFormat. This is useful if you want to format large numbers, use thousand separators, format currency values. It is supported by all evergreen browsers, except Internet Explorer.

Example

  const formatter = new Intl.NumberFormat('de-DE', { 
     style: 'currency', 
     currency: 'EUR' 
  })

  console.log(formatter.format(123456.789));
  // expected output: "123.456,79 €"
Enter fullscreen mode Exit fullscreen mode

Playground

The NumberFormat documentation on MDN is not very clear about the available options, so I decided to build a playground that allows you to customize the formatting options and immediately see the result for a list of locales and input numbers.

In the sidebar you'll find some presets that showcase interesting use cases.

Note: The features marked as V3 will be implemented in a future version of ECMAScript. Therefore, they may not yet be available in your browser yet. I will add a polyfill as soon as it is available.

Open the Codesandbox fullscreen for easy editing. The playground is built in React using the Mantine component library.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more