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!