2

I have read some thousand comma separator JavaScript question/answer but found it hard to apply it in practice. For example I have the variable

x = 10023871234981029898198264897123897.231241235

How will I separate it in thousands with commas? I want a function that not only works with that number of digits but more. Regardless of the number of digits the function I need has to separate the number in commas and leaving the digits after the decimal point as it is, Can anyone help? It has to work on number and turn it into string.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user2197789
  • 105
  • 1
  • 8
  • 1
    *"but found it hard to apply it in practice"*: Please show us what you tried and tell us what exactly you are having problems with. A link to the answer you tried to apply would be great too! Note that the number you mentioned in your post cannot be represented as number in JavaScript with that precision. – Felix Kling Apr 04 '13 at 10:38

1 Answers1

1

First of all, for such huge numbers you should use string format:

var x = "10023871234981029898198264897123897.231241235";

Otherwise, JavaScript will automatically convert it to exponential notation, i.e. 1.002387123498103e+34.

Then, according to the question about money formatting, you can use the following code:

x.replace(/(\d)(?=(\d{3})+\.)/g, "$1,");

It will result in: "10,023,871,234,981,029,898,198,264,897,123,897.231241235".

Community
  • 1
  • 1
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • document.getElementById("result_new_gallons").innerHTML=addcomma(new_gallons); – user2197789 Apr 04 '13 at 10:56
  • var addcomma = function(x){ x = String(x); x = x.replace(/(\d)(?=(\d{3})+\.)/g, "$1,"); } document.getElementById("result_new_gallons").innerHTML=addcomma(new_gallons); Why does it return undefined? – user2197789 Apr 04 '13 at 10:57
  • @user2197789 Because `addcomma` doesn't return the modified `x` value. – VisioN Apr 04 '13 at 10:59