Skip to Content

Format Numbers as Currency Strings in JavaScript

In this tutorial, you'll learn how to format numbers as currency strings in JavaScript using the Internationalization API, a JavaScript API designed to support different languages on a web page.

Currency Formatting

In its simplest form, we can format any plain number into a currency format for a specific language. In this case, we'll format the number 2500 to USD using the Intl.NumberFormat() method:

var formatter = new Intl.NumberFormat(
"en-US", {
style: "currency",
currency: "USD"
}
);

var amount = formatter.format(2500);
// $2,500.00

The first parameter of our method accepts the value en-US, for English in the United States, followed by an object containing two additional parameters: style and currency. The style variable is used to determine the way the numeric value will be formatted, while the currency variable determines the symbol used. For USD, it's the dollar sign at the beginning of the formatted number.

Additional Parameters

There are a couple of additional parameters that may be useful when you format numbers as currency strings in JavaScript:

  • minimumFractionDigits: The number of digits shown to the right of the decimal point. For example, setting the parameter's value to 0 will output this number as $2,500, while setting its value to 1 will output this number as $2,500.0, etc.
  • maximumFractionDigits: The number of digits shown to the right of the decimal point, but rounded up. For example, we'll assume our dollar amount is now $2,500.49. By setting the parameter's value to 0, the dollar amount becomes $2,500. By setting the value to 1, the dollar amount is $2,500.5. And, by setting the value to 2, the dollar amount remains untocuhed as $2,500.49. If our dollar amount was $2,500.99 instead, the new dollar amount would become $2,501.

Conclusion

This was a brief tutorial showing you how to format numbers as currency strings in JavaScript using the Internationalization API. Play around with the function and its parameters to see how the different outputs work.

Created: May 31, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.