The article says to watch out for 0.1 + 0.2 not exactly equalling 0.3 , so as a complete newbie to JavaScript, how do you work around this ?
Consider the following:
.1 + .2 == .3 // false
The way to 'get around' this is to have a value (usually called an epsilon) that is relative in magnitude to the numbers being compared. In this example, a value like .00001 as epsilon should work fine.Anyways, all you have to do is check if the absolute difference of the numbers is less than the epsilon:
var a = .1 + .2, b = .3, epsilon = .00001;
console.log(Math.abs(a-b)<epsilon); // true
In short, try to not put yourself in a situation where you have to compare equality with doubles. var SCALE = 100; // 0.01
var a = 0+1 * SCALE; // e.g. 2.5 would be 2+5 * SCALE
var b = 0+2 * SCALE;
if (a + b == 0+3 * SCALE) {
// this will work...
}
console.log(a / SCALE);Approximate Range -> (-7.9 x 1028 to 7.9 x 1028) / (100 to 28)
Precision -> 28-29 significant digits
Homework: 1) Google for such; 2) see which one doesn't suck.