views:

131

answers:

2

Javascript converts a large INT to scientific notation when the number becomes large. How can I prevent this from happening?

Thanks!

+1  A: 

Use .toPrecision, .toFixed, etc. You can count the number of digits in your number by converting it to a string with .toString then looking at its .length.

Kinopiko
what if I don't know how many digits my integer is?
chris
for some reason, toPrecision doesn't work. if you try: window.examplenum = 1352356324623461346, and then say alert(window.examplenum.toPrecision(20)), it doesn't pop up an alert
chris
actually it pops up sometimes showing scientific notation, and other times it doesn't pop up at all. what am i doing wrong?
chris
+2  A: 

There's Number.toFixed, but it uses scientific notation if the number is >= 1e21 and has a maximum precision of 20. Other than that, you can roll your own, but it will be messy.

function toFixed(x) {
  if (x < 1.0) {
    var e = parseInt(x.toString().split('e-')[1]);
    if (e) {
        x *= Math.pow(10,e-1);
        x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
    }
  } else {
    var e = parseInt(x.toString().split('+')[1]);
    if (e > 20) {
        e -= 20;
        x /= Math.pow(10,e);
        x += (new Array(e+1)).join('0');
    }
  }
  return x;
}

Above uses cheap-'n'-easy string repetition ((new Array(n+1)).join(str)). You could define String.prototype.repeat using Russian Peasant Multiplication and use that instead.

Alternatively, you could use a BigInt library.

outis
thanks, probably the best solution!
chris