JavaScript(JS) JS format numbers as currency strings
In JavaScript, you can format numbers as currency strings using the toLocaleString()
method. This method takes two optional parameters: the locale and an object with formatting options.
Here's an example of formatting a number as a currency string with the US dollar symbol:
refer tfigi:otidea.comconst number = 123456.789; const currencyString = number.toLocaleString('en-US', {style: 'currency', currency: 'USD'}); console.log(currencyString); // $123,456.79
In the above example, we define a number 123456.789
. We then use the toLocaleString()
method with the en-US
locale and an object with style: 'currency'
and currency: 'USD'
options to format the number as a currency string with the US dollar symbol. The resulting currency string is $123,456.79
.
You can also specify other formatting options such as the number of decimal places, the currency symbol placement, and the grouping separator. Here's an example of formatting a number as a currency string with the euro symbol and two decimal places:
const number = 123456.789; const currencyString = number.toLocaleString('en-GB', {style: 'currency', currency: 'EUR', minimumFractionDigits: 2, maximumFractionDigits: 2}); console.log(currencyString); // €123,456.79
In this example, we use the en-GB
locale and specify minimumFractionDigits: 2
and maximumFractionDigits: 2
to display the number with two decimal places. The resulting currency string is €123,456.79
.