Why does this happen to Float value?

And how to prevent it?

var float:Float = 0;

for (i in 0...10)
{
	float += 0.1;
	trace(float);
}

trace gives this:

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

thanks

Thanks @player_03. That’s a great video explaining why that’s the case.

Here’s an alternate explanation. It doesn’t really address your original question, but it explains some other concepts and it’s entertaining.

:slight_smile:

I’m using this as a fix:

float = Math.round(float * 10) / 10;

Is there a better way? I’m only interested in increments of 0.1 in my case.

That ought to work. Another option is to store it as an integer, and then divide by 10 before displaying it.

Thanks for your help, @player_03.

Same problem here: do “9.7 * 100” and you wlll get “969.9999999999999”, while if you do “9.7 * 10 * 10” (with a loop) you will get “970” :open_mouth:
“round, fround, ceil, floor…” etc don’t always fix the problem.

Generally these kind of problems arises in the worst moments… :triumph: