How to Format a Number as a Currency in JavaScript
Table of Contents
Because of how different each country/region formats it, properly formatting a currency from a number is difficult.
For example, in the US, a comma is used to separate the thousands, but in France, a dot is used to separate the thousands.
In this post, we'll learn the proper way to convert a number to a currency.
Converting a number to a currency
First let's start out with our value:
JAVASCRIPTconst value = 25;
Let's say we want to be able to convert this to $25.00
. The best way to do this is to use JavaScript's internationalization API.
Included in this API is a number formatter that supports currency.
Let's define a number formatter that we can use to format 25
into $25.00
.
JAVASCRIPTconst formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2
});
Now, using this formatter object, we just need to call the format
function and pass in the number you want to format.
JAVASCRIPTconst value = 25;
const formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2
});
const formatted = formatter.format(value);
console.log(formatted);
BASH$25.00
The style
property is used to designate that we want to format the number as a currency.
The currency
property is used to specify the currency, in this case, it's USD
.
The minimumFractionDigits
property is used to specify the minimum number of digits after the decimal, which for currencies is usually 2
.
The cool part about this API is that switching to euros in France is as simple as changing the currency
property to EUR
and en-US
to fr-FR
.
JAVASCRIPTconst value = 25;
const formatter = new Intl.NumberFormat("fr-FR", {
style: "currency",
currency: "EUR",
minimumFractionDigits: 2
});
const formatted = formatter.format(value);
console.log(formatted);
BASH25,00 €
This API and number formatter takes the hard work out of formatting currencies for you.
Conclusion
In this post, we learned how to convert a number to a currency.
Simply invoke the format
function from the Intl.NumberFormat
object and pass in the number you want to format.
Thanks for reading and happy coding!
- Getting Started with Svelte
- Git Tutorial: Learn how to use Version Control
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js