Write a JavaScript Program to Format Numbers as Currency Strings

Formatting numbers as currency strings is a common task in web development.

JavaScript provides several built-in methods for converting numbers to currency strings.

In this tutorial, we’ll explore some of these methods and learn how to format numbers as currency strings using JavaScript.

Method 1: toLocaleString()

The toLocaleString() method is a built-in JavaScript method that formats a number according to the locale and options provided.

By default, it formats a number with a comma separator for the thousands and a dot separator for the decimals.

Here’s an example of how to use the toLocaleString() method to format a number as a currency string:

const price = 1234.56;
const formattedPrice = price.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
console.log(formattedPrice); // "$1,234.56"

In the above example, we passed two arguments to the toLocaleString() method: the first argument is the locale, which is set to ‘en-US’ for US English, and the second argument is an options object that specifies the style and currency.

Method 2: Intl.NumberFormat()

The Intl.NumberFormat() constructor is another built-in JavaScript method that provides more control over the formatting of numbers.

It allows you to specify the locale, style, currency, and other formatting options.

Here’s an example of how to use the Intl.NumberFormat() constructor to format a number as a currency string:

const price = 1234.56;
const formattedPrice = price.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
console.log(formattedPrice); // "$1,234.56"

In the above example, we first created an instance of the Intl.NumberFormat() constructor by passing two arguments: the locale and an options object that specifies the style and currency.

We then called the format() method on the formatter object to format the number as a currency string.


Conclusion

In this blog post, we explored two built-in JavaScript methods for formatting numbers as currency strings: toLocaleString() and Intl.NumberFormat().

These methods provide a simple and flexible way to format numbers for display in web applications.