Is there a reasonably fast way to extract the exponent and mantissa from a Number in Javascript?
AFAIK there\'s no way to get at the bits behind a Number in Javascri
While I liked the accepted solution, using it to work on arbitrary base re-introduced all of the errors caused by Math.log
and Math.pow
. Here is a small implementation for any base: x = mantisse * b^exponent
function numberParts(x, b) {
var exp = 0
var sgn = 0
if (x === 0) return { sign: 0, mantissa: 0, exponent: 0 }
if (x<0) sgn=1, x=-x
while (x>b) x/=b, exp++
while (x<1) x*=b, exp--
return { sign: sgn, mantissa: x, exponent: exp }
}
The NaN and Infinite cases can easily be added. If the distinction between +0
and -0
is important:
if (1/x === Infinity) return { sign: 0, mantissa: 0, exponent: 0 }
if (1/x === -Infinity) return { sign: 1, mantissa: 0, exponent: 0 }
What about following to get the exponent?:
let exp = String(number.toExponential());
exp = Number(exp.substr(exp.lastIndexOf('e')+1));
1000 will result in exp = 3