I use this code to separate my number with comma:
jQuery(this).val((jQuery(this).val().replace(/(\d{3}(?!,))/g, "$1,")));
- if my number is
12345
it will become123,45
- but I want the separating comma from the right, i.e.
12,345
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
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)
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