How to Format Numbers as Currency String
This tutorial provides useful information about the formatting number as currency strings. Read and learn several methods you can use to solve your problem.
The number presented as monetary value is readable and eye-catching. If the number has more than three digits, it should be displayed differently. For instance, writing 1000 is not as clear and nice as $1,000. In this case, the currency is USD. However, different countries have other conventions for displaying values.
NumberFormat
The <kbd class="highlighted">Intl.NumberFormat</kbd> object is a constructor for objects enabling language-sensitive number formatting. This method is considered as the modern and fast way for formatting numbers.
javascript format number
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
formatter.format(2000) // "$2,000.00"
formatter.format(20) // "$20.00"
formatter.format(215241000) // "$215,241,000.00"toFixed
Another fast solution is compatible with every major browser:
Javascript format number
All you need is to add the currency symbol and get the amount in the specified currency such as:
javascript format number
console.log("$" + profit.toFixed(3));Note: toFixed does not add thousand separators, which are required for proper currency display. Use Intl.NumberFormat or toLocaleString for full formatting.
toLocaleString
Another solution is <kbd class="highlighted">toLocaleString</kbd>, which offers the same functionality as <kbd class="highlighted">Intl.NumberFormat</kbd>, but <kbd class="highlighted">toLocaleString</kbd> in pre-Intl does not support locales, and it uses the system locale.
Javascript format number
Parameters
Parameters are locales and options. The locales are made up of language code and the country code, such as 'en' for English (language). There are lots of options, and one of them is style. The style is for number formatting. The three values are:
- decimal (plain number formatting)
- currency (currency formatting)
- percent (percent formatting)
Choosing a different locale and currency will format the monetary value accordingly.