Please help with this function

W

WWKougar

Hi all
Wonder if I could have a point in the right direction with the
creation of this function I call RoundHalf


Option Compare Database
Option Explicit
'X is either a temperature or gravity Value
Dim X As Single

Function RoundHalf(X)
TX = Int(X)
Diff = X - TX
If Diff >= 0 Then SIGN = 1.0
Else: SIGN = -1.0
Diff = Abs(Diff)
If Diff < 0.25 Then X = TX
If Diff >= 0.75 Then X = TX + 1.0 * SIGN
Else: X = TX + 0.5 * SIGN

End Function



I would like the function to round a temperature or a density calculation
to the nearest .5 of a degree. If the value is less than or equal to .25 of
a degree, it rounds down. If it is Greater than or equal to .75 of a degree
it rounds up. Anything else, it rounds to .5


Thanks in advance
wwkougar
 
A

Allen Browne

The function below converts the input to a decimal subtype so as to avoid
the rounding errors associated with the Single and Double types.

The return value is a variant of subtype Double, or whatever was passed in
if it wasn't a number.

Function RoundHalf(varNum) As Variant
Dim varResult As Variant

If Not IsError(varNum) Then
If IsNumeric(varNum) Then
varResult = CInt(2 * CDec(varNum)) / 2
End If
End If

If IsEmpty(varResult) Then
RoundHalf = varNum
Else
RoundHalf = varResult
End If
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top