Formatting Numbers with Thousands Separators in JavaScript
Question:
How to use JavaScript to convert integers Format as number with thousands separator? For example, display the number 1234567 as "1,234,567".
Current implementation:
function numberWithCommas(x) { x = x.toString(); var pattern = /(-?\d+)(\d{3})/; while (pattern.test(x)) x = x.replace(pattern, ","); return x; }
A simpler and more elegant method:
function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }
This method uses regular expressions Expression to find occurrences after every three digits (B(?=(d{3}) (?!d))) and replace it with a comma (,).
Floating point number processing:
This method can also handle floating point numbers. Just convert the floating point number into a string and then format it:
const numberWithCommas = (x) => x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); console.log(numberWithCommas(1234567.89)); // "1,234,567.89"
The above is the detailed content of How to Format Numbers with Thousands Separators in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!