I need to get the value of an extremely large number in JavaScript in non-exponential form. Number.toFixed
simply returns it in exponential form as a string, which is worse than what I had.
This is what Number.toFixed
returns:
>>> x = 1e+31
1e+31
>>> x.toFixed()
"1e+31"
Number.toPrecision
also does not work:
>>> x = 1e+31
1e+31
>>> x.toPrecision( 21 )
"9.99999999999999963590e+30"
What I would like is:
>>> x = 1e+31
1e+31
>>> x.toNotExponential()
"10000000000000000000000000000000"
I could write my own parser but I would rather use a native JS method if one exists.
The answer is there's no such built-in function. I've searched high and low. Here's the RegExp I use to split the number into sign, coefficient (digits before decimal point), fractional part (digits after decimal point) and exponent:
"Roll your own" is the answer, which you already did.
You can use
toPrecision
with a parameter specifying how many digits you want to display:However, among the browsers I tested, the above code only works on Firefox. According to the ECMAScript specification, the valid range for
toPrecision
is 1 to 21, and both IE and Chrome throw aRangeError
accordingly. This is due to the fact that the floating-point representation used in JavaScript is incapable of actually representing numbers to 31 digits of precision."10000000000000000000000000000000"?
Hard to believe that anybody would rather look at that than 1.0e+31,
or in html: 1031. But here's one way, much of it is for negative exponents(fractions):
Use Number(string)
Example:
var a=Number("1.1e+2");
gives a=110It's possible to expand JavaScript's exponential output using string functions. Admittedly, what I came up is somewhat cryptic, but it works if the exponent after the
e
is positive: