Formatting Big Numbers in JavaScript

Emmanuel Gautier / March 30, 2023

2 min read

If you've ever worked with large numerical values in JavaScript, you may have encountered the challenge of displaying them in a user-friendly format. For example, imagine you're building a financial application that displays account balances or transaction amounts, and these values can be in the millions or even billions. How do you make sure that users can easily understand these numbers without getting overwhelmed? Fortunately, JavaScript provides several built-in methods and APIs for formatting numerical values, including big numbers.

JavaScript provides several ways to display big numbers in a more readable format. Here are some of them:

Using the toLocaleString() method

The toLocaleString() method returns a string with a language-sensitive representation of a number. It takes two optional arguments: the locale and an object that contains options. By default, it formats the number with the thousands separator and decimal separator according to the user's locale.

For example, to display the number 123456789 in the US English format, you can use:

const number = 123456789;
console.log(number.toLocaleString('en-US'));
// Output: "123,456,789"

Another example to display the same number for in French format this time:

const number = 123456789;
console.log(number.toLocaleString('fr'));
// Output: "123 456 789"

Using the Intl.NumberFormat() constructor

The Intl.NumberFormat() constructor provides a more flexible way to format numbers according to a specific locale. It takes two arguments: the locale and an object that contains options.

For example, to display the number 123456789 in the US English format with a currency symbol, you can use:

const number = 123456789;
const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
console.log(formatter.format(number));
// Output: "$123,456,789.00"

Consulting

If you're seeking solutions to a problem or need expert advice, I'm here to help! Don't hesitate to book a call with me for a consulting session. Let's discuss your situation and find the best solution together.

Share this post
Follow the RSS feed

Subscribe to the newsletter

Get the latest news about tech new articles and projects.