Javascript converts a large INT to scientific notation when the number becomes large. How can I prevent this from happening?
Thanks!
Javascript converts a large INT to scientific notation when the number becomes large. How can I prevent this from happening?
Thanks!
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
.
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.