user10997800
user10997800

Reputation:

I want to separate my digits with a comma from right to left (digit grouping)

I use this code to separate my number with comma: jQuery(this).val((jQuery(this).val().replace(/(\d{3}(?!,))/g, "$1,")));

Upvotes: 3

Views: 597

Answers (3)

Always Helping
Always Helping

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

Toto
Toto

Reputation: 91373

A way to go is to replace

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

with

  • ,

Demo & explanation

Upvotes: 1

Ihor Vyspiansky
Ihor Vyspiansky

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

Related Questions