Out of interest and not real life demands: Is it somehow possible to subtract exponents of two numbers in JavaScript? Because the result of 1e+29 * 1e-3
(or 1e+29 / 1e+3
) is the unprecise number 9.999999999999999e+25
even though the correct result 1e+26
can be expressed in JavaScript.

- 7,517
- 5
- 42
- 54
-
1You might find this question interesting: http://stackoverflow.com/questions/9383593/extracting-the-exponent-and-mantissa-of-a-javascript-number – Abraham P Feb 23 '13 at 00:38
3 Answers
There must be cleaner ways of doing it, but one option would be to convert your number to a string, operate on it, and then convert it back to a number:
function exp_add(num,exp) {
var split = num.toExponential().split('e');
var exponent = parseInt(split[1],10);
exponent += exp;
return parseFloat(split[0] + "e" + exponent);
}
Working example at jsFiddle.

- 21,755
- 7
- 70
- 112
You could use Math.log(1e29)/Math.LN10
, however that yields 28.999999999999993
. Base 2 is just inexact for these numbers. So our last resort is Number.prototype.toString
, which correctly yields "1e29"
. How can we use that now?
function toExp(num) {
return num.toExponential().split("e").map(Number);
// num.toString() only works for num <= 1e-6 and num >= 1e21
}
function fromExp(exp) {
return exp[0] * Math.pow(10, exp[1]);
// or: parseFloat(exp[0]+"e"+exp[1]);
}
function expMultiply(a, b) {
return [ a[0]*b[0], a[1]+b[1] ];
}
function expDivide(a, b) {
return [ a[0]/b[0], a[1]-b[1] ];
}
> fromExp(expMultiply(toExp(1e29), toExp(1e-3)))
1e+26
> fromExp(expDivide(toExp(1e29), toExp(1e3)))
1e+26

- 630,263
- 148
- 957
- 1,375
You will naturally see this as a result of floating point division, especially when one number is much smaller than the other. But, if the numbers have the same base, maybe you should just store their exponents. Otherwise, you can use the logarithm:
( Math.log(1e29) + Math.log(1e-3) ) / Math.LN10
> 25.999999999999993
You may want to just round that result to a few decimal places to take care of the inaccuracy and obtain the result in base 10.

- 35,740
- 23
- 143
- 224