Click here to Skip to main content
14,979,167 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to print an decimal in JavaScript with commas as thousands separators.

JavaScript
function numberWithCommas(number) {
   return number.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}


That regex working good on android, but breaks in iOS (safari, event chrome)

Invalid regular expression: invalid group specifier name


Please help!!

What I have tried:

using old regex instead

JavaScript
function addCommas(nStr) {
         nStr += '';
         var x = nStr.split('.');
         var x1 = x[0];
         var x2 = x.length > 1 ? '.' + x[1] : '';
         var rgx = /(\d+)(\d{3})/;
         while (rgx.test(x1)) {
             x1 = x1.replace(rgx, '$1' + ',' + '$2');
         }
         return x1 + x2;
}
Posted
Updated 26-Jul-20 20:03pm

1 solution

Try:
Option 1:
JavaScript
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Option 2:
Use Number.prototype.toLocaleString[^].
It was implemented in JavaScript 1.5 (introduced way early in 1999) so should be supported across by all browsers.
JavaScript
var n = 12345678.123
n.toLocaleString() // return "12,345,678.123"
   
v2
Comments
GinCanhViet 27-Jul-20 3:02am
   
This option1 the function adds commas in undesirable places if there are more than 3 digits after the decimal point
Sandeep Mewara 27-Jul-20 3:11am
   
Try:
function numberWithCommas(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900