Possible duplicate:
Why decimal numbers cannot be represented exactly in binary format?
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 goal of this cycle is to read 1.0, 1.1, 1.2, 1.3, 1.4, and then move on to 2.0, 2.1, 2.2, etc.
The problem I am getting is that the if
never true. Also, every tenth calculation allows some kind of crazy scientific answer.
How to fix it? please, help!
Edit: I wrote the question in a slightly frustrated rush, and it was a few, I see it now.
The first part of the question was actually βhow can I do this work bypassing this piece with a floating pointβ and βwhy does this querk even happen!β
Thanks for all the great answers, and I vote for the answer correctly, which easily answered the basic question "how to make this work."
Uses 0.49 instead of 0.5 and> instead of ==. Raw and not the best code in the world, but it solves the original question. Thanks to everyone for the other answers that I am going to read and monitor the improvement of my coding.
Thanks again.
source share