How to Convert Numbers to Currency String in javascript


In Javascript applications, You can store data as numbers and display the data in currency strings.

For example, In commerce web application, Each product is displayed with price. Suppose, Application shows dollar as currency to US users and display it in Rupees to Indian users.

Every language provides Internalization API to display the localized formatted data.

javascript provides default localization and Internalization API to convert localized string format.

Intl.NumberFormat to convert Number into Currency String

Intl.NumberFormat class used to convert to language specific strings First Create a NumberFormat class

var formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  //minimumFractionDigits: 0,
  //maximumFractionDigits: 0, 
});

You need to provide this attributes

  • locale string which contains language code and country code, examples ie en-US,ie en-IN,de-DE,ja-JP
  • currency string if style is currency,values are USD,EUR,JPY, This displays the symbol to currency if style=unit values are liter, kilometer-per-hour
  • style : - currency,unit

You can check more about this class here

Here is an complete example

const number = 100000;
console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number)); //"$100,000.00"


console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));//"100.000,00 €"


console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));// "¥100,000"


console.log(new Intl.NumberFormat('en-IN', { }).format(number)); 
//"1,00,000"

console.log(new Intl.NumberFormat('ar-EG').format(number));
// "100,000"

number format as currency string using toLocaleString

toLocaleString convert the number to localized currency string

Here is an example

const number = 1000000;

console.log(number.toLocaleString('en-US', { style: 'currency', currency: 'USD' })); //$1,000,000.00

console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));//1.000.000,00 €

console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' })); // ¥1,000,000

console.log(number.toLocaleString('en-IN', { style: 'currency', currency: 'INR' })); //₹10,00,000.00
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.