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!