This tutorial shows how to format numbers as currency strings in JavaScript. In JavaScript, we can do this by:
- Using
Intl.NumberFormat()
- Using
toLocaleString()
- Using RegEx
Example 1: Using Intl.NumberFormat()
// program to format numbers as currency string
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
console.log(formatter.format(5500));
Output
$5,500.00
Example 2: Using toLocaleString()
// program to format numbers as currency string
const example = (5500).toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
});
console.log(example);
Output
$5,500.00
Example 3: Using Regex
// program to format numbers as currency string
const result = 5500.1234.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
console.log('$ ' + result);
Output
$ 5,500.12