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

How to Format Numbers with Commas in JavaScript?

Barbara Streisand
Release: 2024-12-22 05:48:16
Original
252 people have browsed it

How to Format Numbers with Commas in JavaScript?

Formatting Numbers with Commas as Thousands Separators in JavaScript

When presenting large numbers in JavaScript, it's often desirable to format them with commas as thousands separators for readability. While several methods exist, here are some recommendations and a simplified approach.

One common approach is to use a regular expression to replace every three digits not preceded by a period with a comma. This can be implemented as follows:

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, ",");
    return x;
}
Copy after login

However, for a simpler solution, consider the following:

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

This function replaces every three digits not immediately followed by a decimal point with a comma.

To test the functionality, below is a series of test cases:

function test(x, expect) {
    const result = numberWithCommas(x);
    const pass = result === expect;
    console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
    return pass;
}

let failures = 0;
failures += !test(0,        "0");
failures += !test(100,      "100");
failures += !test(1000,     "1,000");
failures += !test(10000,    "10,000");
failures += !test(100000,   "100,000");
failures += !test(1000000,  "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
    console.log(`${failures} test(s) failed`);
} else {
    console.log("All tests passed");
}
Copy after login

By running these tests, you can verify the accuracy of both approaches for various numeric values.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template