Possible Duplicate:
Why can't decimal numbers be represented exactly in binary?
problem with floating values
$var1 = 1;
for ( $i=0; $i<30; $i++ ) {
$var1 += 0.1;
$var2 = floor($var1);
$var3 = $var1-$var2;
if ( $var3 == 0.5 ) {
$var1 = $var2+1;
}
}
The intention of this loop is to count 1.0, 1.1, 1.2, 1.3, 1.4, and then jump to 2.0, 2.1, 2.2 etc
The problem I'm getting is that the if
statement is never true. Also every tenth calculation resolves to some insane scientific answer.
How do I fix this? please help!
Edit: I wrote the question in a bit of a frustrated rush and it was more than one, I see that now.
The first part of the question really was "how can I make this work by-passing this floating point querk" and "why is this querk even happening!"
Thank you for all the great replies and I'm voting the answer as correct that easily answered the core question of "how to make this work".
Using 0.49 instead of 0.5 and > instead of == does it. Crude and not the best code in the world but it does solve the original question. Thank you to everyone for the other responses that I am going to read and follow up on to improve my coding.
Once again, many thanks.