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.

1
  • 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. Commented Apr 4, 2013 at 10:38

1 Answer 1

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".

Sign up to request clarification or add additional context in comments.

3 Comments

document.getElementById("result_new_gallons").innerHTML=addcomma(new_gallons);
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 Because addcomma doesn't return the modified x value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.