Reputation:
I use this code to separate my number with comma:
jQuery(this).val((jQuery(this).val().replace(/(\d{3}(?!,))/g, "$1,")));
12345
it will become 123,45
12,345
Upvotes: 3
Views: 597
Reputation: 14570
If your number
is a string
or number
itself with no comma at all then You can simply use toLocaleString method to display commas
between thousands
Demo:
let str1 = parseInt('1234').toLocaleString('en')
let str2 = parseInt('12345').toLocaleString('en')
let str3 = parseInt('123456').toLocaleString('en')
console.log(str1)
console.log(str2)
console.log(str3)
Upvotes: 5
Reputation: 916
Did you try the following?
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log(numberWithCommas(12345)); // Output: "12,345"
console.log(numberWithCommas(123456789)); // Output: "123,456,789"
Have a look here for more details - How to print a number with commas as thousands separators in JavaScript
Upvotes: 2