DEV Community

Cover image for Using toLocaleString to display prices in your application
Jackson Lewis
Jackson Lewis

Posted on

Using toLocaleString to display prices in your application

If you have an application that display prices anywhere, such as an ecommerce store, it's very important that those prices are being correctly formatted. As it could cause a real headache if it were to go wrong, particularly if your application needs to support multiple languages and/or currencies.

That's where toLocaleString() comes into play. This method formats number values based on a language code. What's more, you can pass options to specify the style of the number, like a currency!

Let's take a look at how it works.

Using toLocaleString() for currencies

This method can be used for various means of formatting numbers, including when a number needs to be displayed as a currency. Below is the simplest example of using toLocaleString() to display a number as a currency.

// The data
const price = {
    currency: 'GBP',
    amount: 4.99
};

// toLocaleString options
const options = {
    style: 'currency',
    currency: price.currency
};

price.amount.toLocaleString( 'en-GB', options );
// £4.99
Enter fullscreen mode Exit fullscreen mode

Example

Let's go through a step by step example of how we might use this method of displaying a price in a JavaScript application, we'll be using React for this example, however this will work for any website or application that uses JavaScript.

Firstly, let's check out the data we're going to be using.

/**
 * This could be the data object of a product, which contains a price object
 */
const product = {
    ...,
    price: {
        currency: 'GBP',
        amount: 4.99
    },
    ...
};

// Current langauge - this could be set on a backend system and stored globally
const language = 'en-GB';
Enter fullscreen mode Exit fullscreen mode

Now that we have the price data we need, and know what language it should be formatted for, we can create a function that's going to format the data to display a price.

/**
 * Format a price amount based on language and currency
 *
 * @param {object} price The price object
 * @param {string} price.currency The currency to use
 * @param {number} price.amount The raw price amount
 * @return {string} The formatted display price
 */
function formatMoney( price = {} ) {
  return price.amount?.toLocaleString(
    language || 'en-GB', // Provide a default value as a precaution
    {
      style: 'currency',
      currency: price.currency || 'GBP' // Provide a default just in case
    }
  );
}
Enter fullscreen mode Exit fullscreen mode

Perfect! So we pass a price object to the function as the price parameter, and directly return the amount which will get formatted based on the pre-defined language and the currency which is defined within our price object.

You'll also notice from the code snippet above, that we provide fallback values for the language and currency. While this isn't required, it may be a good idea if you believe it's possible either may not be passed a value by their respective variable. It just prevents your app from not displaying a price at all, which would not be good news!

What's so handy about having such a simple function like this is that we can use it everywhere in an ecommerce application. From the product page, to the cart and viewing customer orders, wherever there is a price to display, we'd use this function to correctly display it, as if enforces consistency across our application.

So now let's bring all this together to display a price on the frontend of our application, which will look a little like the following.

/**
 * Render the price on our component
 */
const Product = () => (
  <div>
    <p className="price">{ formatMoney( product.price ) }</p>
  </div>
);
ReactDOM.render( <Product />, document.getElementById( 'root' ) );
Enter fullscreen mode Exit fullscreen mode

It's worth mentioning we're only using React for the example here. As toLocaleString() is native JavaScript, you can apply this to any application where JavaScript is used.

Other methods

Let's not forget, this is the world of web development, meaning there are usually many ways of getting to the same result. If toLocaleString() doesn't float your boat, you may want to take a look at Intl.NumberFormat. Here's how that may look:

new Intl.NumberFormat( 'en-GB', {
    style: 'currency',
    currency: 'GBP'
}).format( 4.99 )
// £4.99
Enter fullscreen mode Exit fullscreen mode

Check out the full working example over on CodePen. Thanks!

Top comments (0)