6

I have javascript code that often outputs very big numbers, that I would like to be displayed fully rather than getting a value such as 2.7934087356437704e+56 I'd like it to display the entire number. Is it possible to make this happen in JS?

Seb
  • 237
  • 3
  • 8
  • 1
    Take a look at the answer here http://stackoverflow.com/questions/4170633/opposite-of-number-toexponential-in-js – TommyBs Apr 17 '13 at 17:56
  • Do you really need 60-digit precision numbers? Who is supposed to read them, what are you computing with them? – Bergi Apr 17 '13 at 18:06

2 Answers2

3

With such a large number, you will lose precision in Javascript. The exponential form it returns is the most precise Javascript can represent. However, if you do not care about the loss of precision and just want a string of the expanded number, you can use your own function to do this. I couldn't find a method that will do this natively so you have to add it in yourself.

I found this snippet which will do that for you by Jonas Raoni Soares Silva:

String.prototype.expandExponential = function(){
    return this.replace(/^([+-])?(\d+).?(\d*)[eE]([-+]?\d+)$/, function(x, s, n, f, c){
        var l = +c < 0, i = n.length + +c, x = (l ? n : f).length,
        c = ((c = Math.abs(c)) >= x ? c - x + l : 0),
        z = (new Array(c + 1)).join("0"), r = n + f;
        return (s || "") + (l ? r = z + r : r += z).substr(0, i += l ? z.length : 0) + (i < r.length ? "." + r.substr(i) : "");
    });
};

A usage example would be:

> var bignum = 2.7934087356437704e+56;
> (bignum+'').expandExponential();
"279340873564377040000000000000000000000000000000000000000"

You have to cast the number to a string first, hence the +''

If you really need exact precision you can try using a library like Big Number or javascript-bignum.

nullability
  • 10,545
  • 3
  • 45
  • 63
  • :) the precision doesn't matter too much, I just need it to be the right length in terms of number of digits. Thanks! – Seb Apr 17 '13 at 18:22
1

In JavaScript all numbers are floating point numbers so you don't have absolute precision.

Halcyon
  • 57,230
  • 10
  • 89
  • 128