2

I'm trying to set up a simple macro to generate a column of values incremented by a specific value up to a specific value. For the current example, I want to produce a column ranging from 0 to 97.9 and incremented by 0.1. Here is the code I use:

Set Inp = Workbooks("Effective Weight.xlsm").Worksheets("Input")
Set Res = Workbooks("Effective Weight.xlsm").Worksheets("Results")

i = 1
Res.Cells(i, 1) = 0

Do While Res.Cells(i, 1) <= 97.9
    Res.Cells(i + 1, 1) = Res.Cells(i, 1) + 0.1
    i = i + 1
Loop

MsgBox (Res.Cells(i, 1))

This results in a final value of 97.9999999999987. I was expecting to be 97.9. because of the higher number of decimal points, the loop also runs one extra loop and calculates a final value of "almost" 98 instead of 97.9.

Any help on how to solve this will be appreciated

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
xaos9
  • 29
  • 1
  • 1
    You can use a `Long` variable to increment integers and devide it by 10 to get your actual floating number (so you increment by `1` instead of `0.1` end your loop at `979` instead of `97.9` and devide the result by `10` to get the real value you were looking for). This would prevent your issue. Incrementing integer numbers is absolute (exactly), but incrementing floating point numbers like `0.1` is always just approximately `0.1` never exactly (due to the general design of how computers and calculators work, see the link above your question). – Pᴇʜ Jun 18 '19 at 07:17

0 Answers0