View Single Post
  #6   Report Post  
Posted to microsoft.public.excel.programming
Rick Rothstein \(MVP - VB\)[_1946_] Rick Rothstein \(MVP - VB\)[_1946_] is offline
external usenet poster
 
Posts: 1
Default for loop with step increment of 0.1

The problem has to do with floating point representation and the inability
of VB (actually, any language) of being able to store all fractions in a
given integer data type (the problem is akin to the decimal representation
of 2/3, a decimal point followed by an unending string of 6's, invariably
the number is written as a fixed number of 6's followed by an ending 7)...
whatever has accumulated in the loop variable "i" at the 1.9 stage, adding
0.1 to it gives a number ever so slightly greater than 2 which is outside of
the ending loop limit, hence the loop ends at the 1.9 value. The way around
this problem is to not use floating point numbers. For example...

Sub test()
For i = 15 To 20
Debug.Print i / 10
Next i
End Sub

(note the modified loop limits) where whenever you would have used "i" in
your original loop code, you would use "i/10" instead.

Rick


"choi4u" wrote in message
...
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.