How to format a number as a currency value in JavaScript

Learn how to use the JavaScript Internationalization API to convert numbers to currency values

Suppose you have a similar10, It represents the price of something.

You want to convert it to$10,00.

If the number is more than 3 digits, it should be displayed in a different way, for example1000Should show up as$1,000.00

But this is the U.S. dollar.

Different countries have different conventions to show value.

JavaScript makes it easy for usECMAScript Internationalization API, This is a relatively new browser API that provides many internationalization features, such as date and time formats.

It is well supported:

Browser support for the internationalization API

const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2
})

formatter.format(1000) // “$1,000.00” formatter.format(10) // “$10.00” formatter.format(123233000) // “$123,233,000.00”

ThisminimumFractionDigitsThe attribute always sets the decimal part to at least 2 digits. You can check which other parameters can be used inNumberFormat MDN page.

This example creates a number formatter for the euro for the Italian country/region:

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

Download mine for freeJavaScript beginner's manual


More js tutorials: