Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"For" loops increment not working correctly. Why?

for (float i = -1; i <= 1; i+=0.1f)   
{
    Console.WriteLine(i);   
}

This is results

-1
-0.9
-0.8
-0.6999999
-0.5999999
-0.4999999
-0.3999999
-0.2999999
-0.1999999
-0.09999993
7.450581E-08
0.1000001
0.2000001
0.3000001
0.4000001
0.5000001
0.6000001
0.7000001
0.8000001
0.9000002
like image 883
Artur Keyan Avatar asked Jul 28 '11 10:07

Artur Keyan


1 Answers

Because a float is not an exact decimal number but a floating point number. Use decimal instead.

See wikipedia for reference: Wikipedia

like image 127
Maximilian Mayerl Avatar answered Sep 28 '22 09:09

Maximilian Mayerl