# For loop unexpected end value

Hi, When experimenting with a for loop in c# I have an unexpected final value. The first code loop below shows an expected result with the values 0 - 1 printed to the output window in steps of 0.1. However the second example ends with a value of 0.95! Other step values such as 0.2, 0.25 work ok and ends on 1. But for some reason any step values below 0.1 don't end on 1, such as 0.05, 0.025, 0.01 etc.

Any explanation for this would be greatly appreciated. plus how I can make sure it always ends on 1 assuming the step value is entirely divisible into 1 with no remainder.
``````for (double i = 0; i <= 1; i += 0.1)
{
Debug.WriteLine(i);
}

for (double j = 0; j <= 1; j += 0.05)
{
Debug.WriteLine(j);
}
``````
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
You should never count on having correct resultt when dealing with double variables. Why your code is not displaying the last j value (which should be 1) is because it is slightly larger than 1

ex

1.0000000000252

This is why, when using doubles in loop, you need to do next

``````for (double i = 0; i <= 1.01; i += 0.1)
{
Debug.WriteLine(i);
}

for (double j = 0; j <= 1.01; j += 0.05)
{
Debug.WriteLine(j);
}
``````
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
Add watch to j varaible and see what its value is when it loops.
0
Commented: