I'd like to take a comma in a thousand digits when I print the integrer in JavaScript. For example, If you have 1234567, I want to print it out like 1,234,567
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
I did it like this. But is there a simpler and better way than this?
javascript format
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
© 2024 OneMinuteCode. All rights reserved.