3

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 become 123,45
  • but I want the separating comma from the right, i.e. 12,345
Always Helping
  • 14,316
  • 4
  • 13
  • 29

3 Answers3

4

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)
Always Helping
  • 14,316
  • 4
  • 13
  • 29
  • This is the best internationalized way, as `,` is not everywhere the grouping separator and 3 digits is not everywhere the grouping amount. In DE/AT/FR a proper grouping would be `1.024.000`, in CH a proper grouping would be `2'048'000`, in IN it would be `40,96,000`... – AmigoJack Aug 15 '20 at 13:54
2

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

Ihor Vyspiansky
  • 918
  • 1
  • 6
  • 11
1

A way to go is to replace

  • (?<=\d)(?=(?:\d{3})+(?!\d))

with

  • ,

Demo & explanation

Toto
  • 89,455
  • 62
  • 89
  • 125