In this example, you will learn to write a JavaScript program that will format numbers as currency strings.
Đang xem: How to format numbers as currency string in javascript
To understand this example, you should have the knowledge of the following JavaScript programming topics:
Example 1: Format Numbers as Currency String
// program to format numbers as currency stringconst formatter = new Intl.NumberFormat(“en-US”, { style: “currency”, currency: “USD”});formatter.format(2500);Output
$2,500.00In the above program, we have used the Intl.NumberFormat object.
The Intl.NumberFormat object enables language-sensitive number formatting.
Example 2: Format Numbers as Currency String Using concatenation
// program to format numbers as currency stringconst number = 1234.5678;const result = “$ ” + number.toFixed(2);console.log(result);Output
$ 1234.57In the above example, the toFixed(2) method is used to round up the number to two decimal values.
“$” is added to the number to convert it into a currency string.
Example 3: Format Numbers as Currency String Using toLocaleString()
// program to format numbers as currency stringconst result = (2500).toLocaleString(“en-US”, { style: “currency”, currency: “USD”});console.log(result);
Output
$2,500.00The toLocaleString() method returns a string with a language-sensitive representation of that number.
Example 4: Format Numbers as Currency String Using RegEx
// program to format numbers as currency stringconst result = 1234.5678.toFixed(2).replace(/d(?=(d{3})+.)/g, “$&,”);console.warn(“$ ” + result);Output
$ 1,234.57In the above example, the replace() method is used with the RegEx pattern to replace the number to currency string.
The toFixed(2) method is used to round up the number to two decimal values.
Share on:
Did you find this article helpful?
Sorry about that.
How can we improve it?
Feedback *
Leave this field blank
Related Examples
JavaScript Example
Format the Date
JavaScript Example
Replace Characters of a String
JavaScript Example
Add Two Numbers
JavaScript Example
Replace All Occurrences of a String
Join our newsletter for the latest updates.
This is required.
Join
Join our newsletter for the latest updates.
This is required.
Join
Tutorials
Examples
Company
Apps