Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

The Round() function rounds 2.45 to 2.4 and is correct. Why?

Functions

The Round() function rounds 2.45 to 2.4 and is correct. Why?

by  davemcdonaldireland  Posted    (Edited  )
Before you use the [tt]Round()[/tt] function in Access, please read this FAQ or you may introduce calculation errors into your application:

Syntax: [tt] Round(expression[, numdecimalplaces])[/tt]

The Access Round() function appears to be a handy way of rounding decimal values to a given number of decimal places. For example, [tt]Round(2.341, 2)[/tt] returns 2.34.

However, it does not perform rounding the way you might expect. Take this example:

[tt]Round(2.385,2)[/tt]

You would expect this to return 2.39, but if you open an immediate window and type [tt]?Round(2.385,2)[/tt] you will get the following output:

2.38 (not 2.39)

Even though the last digit was 5, it rounded DOWN.


If this is not the behaviour you expected, then hereÆs the explanation:

The Round() function does a round-to-even, not the more well-known round-to-larger. If the argument ends in 5, the number may be rounded up or down to achieve an even rightmost figure.

So in our example above:

2.385 could be rounded to either 2.38 or 2.39. The former has an even rightmost figure, so this is the result.

The reasoning behind this is to eliminate cumulative errors over a series of calculations. Put another way, 100 half pennies should round to be equal 50 cents, not 100 cents.


A RoundToLarger() function:
[tt]
Public Function RoundToLarger(dblInput As Double, intDecimals As Integer) As Double

'Implements a variant of the Round() function, that rounds-to-larger
'rather than rounds-to-even, like in Excel:

Dim strFormatString As String 'Format string
Dim strResult As String

'If input is zero, just return zero. Else format as appropriate:
If dblInput <> 0 Then
strFormatString = "#." & String(intDecimals, "#")
If Right(strFormatString, 1) = "." Then
strResult = Format(dblInput, "#")
Else
strResult = Format(dblInput, strFormatString)
End If

Else
strResult = "0"
End If

'If the result is zero, Format() will return "." - change this to "0":
If strResult = "." Then
strResult = "0"
End If

RoundToLarger = CDbl(strResult)

End Function
[/tt]

Acknowledgement: Thanks to ôhnawebmasterö for help in compiling this FAQ.


Dave Mc Donald
www.mcdonaldit.com

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top