MarthaPCS said:
I need to calculate a price each to the nearest 1/10th of a cent:
eg:
1.0725 to round to 1.073 (I get 1.072)
1.5145 to round to 1.515 (I get 2.514)
I have rounding set to 3 decimal places but Access 2003 wants to use bankers
rounding and none of the functions in kb/196652 makes any difference in the
result.
This turned out to be more interesting than I thought.
In a query:
Rounded: Int(1000 * [fieldname] + 0.5) / 1000
1.0725 -> 1.073
1.5145 -> 1.515
In VBA (Note: Rnd1, Rnd2, Rnd3 and Rnd4 are alternative rounding
functions, not rounding to that number of places):
Public Function Rnd1(varX As Variant) As Double
Rnd1 = Int(1000# * varX + 0.5) / 1000#
End Function
Rnd1(1.0725) -> 1.073
Rnd1(1.5145) -> 1.515
Public Function Rnd2(dblX As Double) As Double
Rnd2 = Int(1000# * dblX + 0.5) / 1000#
End Function
gives
Rnd2(1.0725) -> 1.073
Rnd2(1.5145) -> 1.514
but
Public Function Rnd3(dblX As Double) As Double
Rnd3 = Int(1000# * CDec(dblX) + 0.5) / 1000#
End Function
gives
Rnd3(1.0725) -> 1.073
Rnd3(1.5145) -> 1.515
Public Function Rnd4(dblX as Double) As Double
Rnd4 = Int(1000# * dblX + 0.500000000000001) / 1000#
End Function
might work, but fails on esthetic grounds.
I think you should do some testing to make sure your discontinuities
behave the way you want.
I actually drew pictures of Int(x), Int(x*1000)/1000 and
Int((x+0.0005)*1000)/1000 (along with filled and unfilled endpoints) to
convince myself that the final function should round to the nearest
0.001 with the midpoint rounding up. Error in the floating point
representation seems to have made 1.5145 look more like 1.5144999999999
with Rnd2().
James A. Fortune
(e-mail address removed)