How to Format a Number with Commas in JavaScript

Formatting numbers with commas as thousands separators is a common requirement for displaying numeric data in a more readable format. JS provides several ways to achieve this, making it easier to present JavaScript numbers in a format that users can understand at a glance.

How Do You Use toLocaleString for basic formatting?

The toLocaleString() method is a part of the Number prototype in JavaScript, allowing numbers to be formatted according to the locale-specific rules. This is the simplest way to format numbers with commas.

const number = 1234567.89; const formattedNumber = number.toLocaleString(); console.log(formattedNumber); // Output: "1,234,567.89" for en-US locale

How can you achieve advanced formatting with Intl.NumberFormat?

For more control over the formatting, the Intl.NumberFormat object can be used. This part of the Internationalization API provides language-sensitive number formatting.

const number = 1234567.89; const formatter = new Intl.NumberFormat('en-US'); const formattedNumber = formatter.format(number); console.log(formattedNumber); // Output: "1,234,567.89"

How to Implement a custom formatting function

In scenarios where you need a custom formatting solution that doesn't rely on the user's locale or the Internationalization API, you can craft a custom function.

function formatNumberWithCommas(number) { return number.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ","); } const number = 1234567.89; const formattedNumber = formatNumberWithCommas(number); console.log(formattedNumber); // Output: "1,234,567.89"

This function converts the number to a string, then uses a regular expression to insert commas at the appropriate positions.

Each of these methods offers a way to format numbers with commas, making it easier for users to read and understand large numbers. The choice of method depends on the specific requirements of your project, such as the need for localization or custom formatting rules.

Invite only

We're building the next generation of data visualization.