0

Let's say I write this in JS:

var product = 50000000*39048902222211111111111111111111:
alert(product); //this gives me 1.9524451111105555e+39.

Is there any way to display the whole number, and not that e+39 thing?

  • With numbers that big, you need some extra library. Native numbers in JS have to be smaller - see [this question](http://stackoverflow.com/q/307179/1169798) – Sirko Mar 02 '14 at 15:51
  • 2
    @Sirko Indeed. you can't print the whole number as javascript doesn't store the whole number. see http://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript – TastySpaceApple Mar 02 '14 at 15:52
  • That value is larger than the [maximum integer precision](http://www.ecma-international.org/ecma-262/5.1/#sec-8.5) that Javascript can handle. To perform such large integer math and maintain precision you will need to use a library like [`bignumber.js`](https://github.com/MikeMcl/bignumber.js) – Xotic750 Mar 02 '14 at 15:58

2 Answers2

2

The integer values you are trying to represent are larger than the integer precision that Javascript can handle (fixed-precision arithmetic). Maximum safe integers are -9007199254740991 to 9007199254740991 or +/-(2^53-1)

While 9007199254740992 can be represented it is considered unsafe. Why? Try this jsFiddle

Javascript

alert(9007199254740992 + 1);

Output

9007199254740992

See specification ecma-262/5.1/#sec-8.5

But you can use a library for arbitrary-precision arithmetic, or roll your own.

Using one such library, bignumber.js, loaded using require.js

Javascript

require.config({
    paths: {
        bignumberjs: 'https://raw.github.com/MikeMcl/bignumber.js/master/bignumber.min'
    }
});

require(['bignumberjs'], function (BigNumber) {
    BigNumber.config({
        EXPONENTIAL_AT: 100
    });

    var product = new BigNumber('50000000').times('39048902222211111111111111111111');

    alert(product);

});

Output

1952445111110555555555555555555550000000

On jsFiddle

Xotic750
  • 22,914
  • 8
  • 57
  • 79
0

Try somthing like this:

Number.prototype.realValue = function(){
    return this.toString().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) : "");
    });
};

Acess the medthod like:

var product = 50000000*39048902222211111111111111111111:
alert(product.realValue())

Sources:Javascript display really big numbers rather than displaying xe+n

Community
  • 1
  • 1
bren
  • 4,176
  • 3
  • 28
  • 43
  • Sorry, but you have a loss of precision. http://jsfiddle.net/Xotic750/bVj6R/ gives `1952445111110555500000000000000000000000` – Xotic750 Mar 02 '14 at 16:09