Introduction
For some calculations I need to find the smallest possible number I can add/subtract from a specified number without JavaScript getting in trouble with the internal used data type.
Goal
I tried to write a function which is able to return the next nearest number to VALUE in the direction of value DIR.
function nextNearest(value, direction) {
// Special cases for value==0 or value==direction removed
if (direction < value) {
return value - Number.MIN_VALUE;
} else {
return value + Number.MIN_VALUE;
}
}
The problem with this is, that JavaScript uses a 64-bit float type (I think) which has different minimum step sizes depending on its current exponent.
Problem in detail
The problem is the step size depending on its current exponent:
var a = Number.MIN_VALUE;
console.log(a);
// 5e-324
console.log(a + Number.MIN_VALUE);
// 1e-323 (changed, as expected)
var a = Number.MAX_VALUE;
console.log(a);
// 1.7976931348623157e+308
console.log(a - Number.MIN_VALUE);
// 1.7976931348623157e+308 (that's wrong)
console.log(a - Number.MIN_VALUE == a);
// true (which also is wrong)
Summary
So how can I find the smallest possible number I can add/subtract from a value specified in a parameter in any direction? In C++ this would be easily possible by accessing the numbers binary values.