Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript display really big numbers rather than displaying xe+n [duplicate]

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?

like image 805
Seb Avatar asked Apr 17 '13 17:04

Seb


2 Answers

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.

like image 71
nullability Avatar answered Oct 11 '22 14:10

nullability


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

like image 37
Halcyon Avatar answered Oct 11 '22 15:10

Halcyon