Home >Web Front-end >JS Tutorial >How Can I Add Commas as Thousands Separators to Numbers in JavaScript?

How Can I Add Commas as Thousands Separators to Numbers in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 03:50:17212browse

How Can I Add Commas as Thousands Separators to Numbers in JavaScript?

Adding Comma Separators to Numbers in JavaScript

In JavaScript, displaying large numbers with thousands separators makes them more readable. Here's a simple yet effective solution:

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

This function replaces every three consecutive digits except the first three with a comma. Let's test it:

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

This method doesn't handle floats or locale-specific formatting, but it provides a straightforward approach for adding commas as thousands separators to integer values.

The above is the detailed content of How Can I Add Commas as Thousands Separators to Numbers 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