JavaScript’s Internationalization API gives access to a whole new world of geological data. It can be utilized in many forms, from Time zone calculation to currency to locale string conversions. Here I’m going to show how you can use the Intl.NumberFormat function to convert numbers in currencies with commas and symbols appended as used in locale. Here’s an example code I’ve written for the same:
const somePrice = 2500000.5
let US_Format = Intl.NumberFormat('en-US')
let IN_FORMAT = Intl.NumberFormat('en-IN')
let DE_FORMAT = Intl.NumberFormat('de-DE')
let EG_FORMAT = Intl.NumberFormat('ar-EG')
console.log('American format: ', US_Format.format(somePrice))
console.log('Indian format: ', IN_FORMAT.format(somePrice))
console.log('German format: ', DE_FORMAT.format(somePrice))
console.log('Arabic format: ', EG_FORMAT.format(somePrice))
//output
American format: 2,500,000.5
Indian format: 25,00,000.5
German format: 2.500.000,5
Arabic format: ٢٬٥٠٠٬٠٠٠٫٥
Code language: JavaScript (javascript)
Another good thing about the format() method is that it can also accept string values for conversion directly:
const somePriceInString = '3141592.65'
let US_Format = Intl.NumberFormat('en-US')
let IN_FORMAT = Intl.NumberFormat('en-IN')
console.log('American format: ', US_Format.format(somePriceInString))
console.log('Indian format: ', IN_FORMAT.format(somePriceInString))
//output
American format: 3,141,592.65
Indian format: 31,41,592.65
Code language: JavaScript (javascript)