Home >Web Front-end >JS Tutorial >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; }
However, for a simpler solution, consider the following:
function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }
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"); }
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!