1 Attachment(s)
[RESOLVED] Round to nearest specified value
I've been using this code to round off values but there is a problem when I try to round to a decimal value. RoundToNearestVal = 0.1 and a Double or Variant type. It takes the value as 0 so I get a division by 0 error. What am I doing wrong here?
Code:
Public Function RoundToNearest(NumberToRound, RoundToNearestVal)
'Function rounds up or down to the nearest value
RoundToNearest = RoundToNearestVal * (NumberToRound \ RoundToNearestVal)
If Abs(NumberToRound - RoundToNearest) > RoundToNearestVal / 2 Then
If NumberToRound >= 0 Then
RoundToNearest = RoundToNearest + RoundToNearestVal
Else
RoundToNearest = RoundToNearest - RoundToNearestVal
End If
End If
End Function
Re: Round to nearest specified value
\ is an operator for Long or Integer data type.
x = 1000 \ 0.1 = CInt(1000) \ CInt(0.1) = 1000 \ 0 : Division by zero!
With Variant/Double, change to:
Code:
RoundToNearest = RoundToNearestVal * Int(NumberToRound / RoundToNearestVal)
Re: Round to nearest specified value
Hi anhn. Not sure I understand. NumberToRound \ RoundToNearestVal still returns <Division by zero> and causes an error.
Why is NumberToRound \ RoundToNearestVal set to a Variant/Integer type in the watch window?
Re: Round to nearest specified value
Just as anhn said, these are implicitly converted to integers or long before division, when you use the \ operator.
Re: Round to nearest specified value
Ohh.. I didn't notice the \ / difference.
Thankyou both!
Re: Round to nearest specified value
\ = integer division
/ = decimal division