View Single Post
  #8   Report Post  
Posted to microsoft.public.excel.programming
T Lavedas T Lavedas is offline
external usenet poster
 
Posts: 38
Default for loop with step increment of 0.1

On May 16, 9:33 am, choi4u wrote:
Running this code
Sub test()
For i = 1.5 To 2 Step 0.1
Debug.Print i
Next i
End Sub

gives this output
1.5
1.6
1.7
1.8
1.9 .

Why does the output not include 2.0?
and what do I have to do to make the output include 2.0?

Thanks in advance.


It's due to the age old binary to decimal conversion problem.
Computers use binary representations of real numbers that often (most
often) do not convert exactly to their decimal equivalents without
some remainder. This leads to the commonly occurring problem that you
see here.

As Dan Guillett suggested, one workaround is simply increase the end
value to compensate for the error, though I might use 2.01 to keep
from confusing the issue more - that is, "Why isn't 2.1 in the list?"
Another approach might be to convert the loop from a FOR to a Do Until
with a Round function to correct for the error ...

Sub test()
step = 0.1
i = 1.5
Do Until i 2
Debug.Print i
i = Round(i + step, 1)
Loop
End Sub

Another way that would work is to round the index in the FOR loop ...

Sub test()
For i = 1.5 To 2 Step 0.1
Debug.Print i
i = Round(i, 1)
Next i
End Sub

Tom Lavedas
===========
http://members.cox.net/tglbatch/wsh/