r/visualbasic • u/skijumptoes • Feb 01 '21
VBA - Could someone please explain the following please (Backslash dividing and floats/doubles)
So, the problem i have is that i had a piece of code that would divide purchase units from stock units.
732ml was the incoming stock, each purchasing unit is 146.4ml.
So i applied the following formula to qualifying incoming purchase qty:-
int(stkQty/purUnits)
i.e.
int(732/146.4) = Expecting a '5'
This doesn't return a 5 as expected, but a 4. I can understand that casting it as an Integer would round down to a 4 (If the returned value was any less than a 5) but i cannot see how it's happening as in the immediates window i can't see any sign of a float value being returned below 5.
i.e.:-
debug.Print int(732.0/146.4) = 4
debug.Print format((732.0/146.4),"Scientific") = 5.00E+00
debug.Print format((732.0/146.4),"0.000000") = 5.000000
But if i apply a backslash (Which i've never come across before):-
debug.Print int(732.0\146.4) = 5
debug.Print format((732.0\146.4),"Scientific") = 5.00E+00
debug.Print format((732.0\146.4),"0.000000") = 5.000000
The crazy thing is that placing a formula in excel 'int(732/146.4)' returns a 5, but if you do the same via a vb script in excel it gives you the 4.
Anyone explain?
3
3
u/MaxObjFn Feb 01 '21
You don't usually see this happen, but it is always a possibility because computers handle floats as approximations. Casting to an integer drops everything behind the decimal so your example is being approximated as some value less than 5. I'd recommend using Math.round.