Loop through a decimal sequence
I am writing a loop in VBA for excel, and I would like to loop through a sequence of decimal numbers, rather than integers.
For example:
For i = 1 To 10
'Do something
Next i开发者_StackOverflow中文版
But rather than incrementibg by 1, I would like to increment by 0.5 (or perhaps 5, or really any number other than 1).
Dim i as Single
For i = 1 To 10 Step 0.5
'
Next
But note you can get some unwanted numbers because of the floating numbers not being precise.
Sub a()
For i = 1 To 10 Step 0.1
Debug.Print i
Next i
End Sub
You can use a decimal generator.
def loop_decimal(loop_start_value, loop_stop_value, loop_step_value = 1):
# Input arguments error check
if not loop_step_value:
loop_step_value = 1
loop_start_value = decimal.Decimal(str(loop_start_value))
loop_step_value = decimal.Decimal(str(loop_step_value))
loop_stop_value = decimal.Decimal(str(loop_stop_value))
# Case: loop_step_value > 0
if loop_step_value > 0:
while loop_start_value < loop_stop_value:
yield loop_start_value
loop_start_value += loop_step_value
# Case: loop_step_value < 0
else:
while loop_start_value > loop_stop_value:
yield loop_start_value
loop_start_value += loop_step_value
Calling the generator produces:
for x in (loop_decimal(0.1, 0.9, 0.1)):
print(x)
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
To convert a float into an exact decimal value, use the str()
in the decimal.Decimal()
command.
decimal.Decimal(str( float_value ))
If you pass None or 0.0 to the step argument, the default value of 1 will be used.
This works for incrementing and decrementing loops.
精彩评论