Home >Web Front-end >JS Tutorial >How Can I Format Numbers with Commas in JavaScript?

How Can I Format Numbers with Commas in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 16:10:11259browse

How Can I Format Numbers with Commas in JavaScript?

Formatting Numbers with Comma Separators in JavaScript

When dealing with large numbers in JavaScript, it's often useful to format them with commas as thousand separators to enhance their readability.

Function for Number Formatting with Commas

One popular approach is to utilize the replace() method and regular expressions. Here's a straightforward function that accomplishes this task:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

This function takes an integer x as an input and returns a string representation with commas inserted as separators for thousands.

Example Usage

Let's test the function with various input values:

console.log(numberWithCommas(0)); // "0"
console.log(numberWithCommas(100)); // "100"
console.log(numberWithCommas(1000)); // "1,000"
console.log(numberWithCommas(10000)); // "10,000"

The above code demonstrates how our function correctly inserts commas into different number representations.

The above is the detailed content of How Can I Format Numbers with Commas in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn