1

When you run a huge sum in JS it comes out with something like : 1.0328135768135768e+21. Is there a way to make it output a pure integer, even if it is very long?

Thanks.

1
  • 1
    No there isn't, if the number is outside the integer range, like in the above example. Commented Jan 19, 2014 at 12:05

1 Answer 1

2

The .toString() method seems to do the trick. Sort of:

1.0328135768135768e+21.toString("10");
// "1032813576813576802460"

1.0328135768135768e+50.toString("10")
// "103281357681357664662886440420862446808642642662440"

Note that (as shown above) because of JS's handling of floating point numbers you don't just get the digits you specified with zeros on the end.

If you wanted all zeros on the end you could always format it yourself:

function formatNumber(n) {
    var s = n + "",
        a = s.split("e");
    if (a.length === 1)
        return s;
    s = a[0].replace(/\./,"");
    s += (new Array(+a[1] - s.length + 2).join("0"));
    return s;
}

Demo: http://jsfiddle.net/HLQQ9/ (Note: not tested thoroughly at all, just a half-baked idea I hacked together to give you a starting point.)

Or there are several big number libraries around.

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

Comments

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.