Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make For loop work with non integers

Tags:

vba

The following code is easy and outputs as expected

CODE:

Option Explicit

Sub Test_loop2()
Dim i As Long
  For i = -3 To 3 Step 1
    Debug.Print i
  Next i
End Sub

OUTPUT:

enter image description here

The following code is exiting early due to rounding

Option Explicit

Sub Test_loop2()
Dim i As Double
  For i = -0.3 To 0.3 Step 0.1
    Debug.Print i
  Next i
End Sub

OUTPUT:

enter image description here

What is the most reliable method I can use whilst retaining a For Loop to ensure the last value is run in the loop for non integers?

Eg For i = X to Y step Z - Y must always be reached if it's multiple of Z

For i = 0 to 0.3 step 0.1 then 0.3 will be in loop

For i = 0 to 0.3 step 0.2 then 0.3 will NOT be in the loop


1 Answers

Floating point arithmetic will eventually screw you if you use a Double (or Single) as counter.

For counters, stick to whole numbers. Then derive your floating point value from that counter. Example:

Dim i As Long
Dim d As Double
For i = 0 To 6
    d = (i - 3) * 0.1 ' or whatever formula needed
    Debug.Print d
Next i
like image 72
Jean-François Corbett Avatar answered Nov 24 '25 23:11

Jean-François Corbett