2

I am using python 3.8.5 and rounding decimals and not floats which can behave strangely.

Python normally rounds all decimal.Decimals properly where .50 are rounded up.

However, only Decimal(1120.50) is rounding down. What could be the error in my code.

To recreate

import decimal

round(decimal.Decimal(1119.50))
# OK: Expected output 1120, actual output 1120

round(decimal.Decimal(1120.50))
# Wrong: Expected output 1121, actual output 1120

round(decimal.Decimal(1121.50))
# OK: Expected output 1122, actual output 1122

Any help would be appreciated.

Thanks

Tanshu
  • 23
  • 2
  • The default is to round X.5 to the nearest even number; this avoids the bias that would result if you always rounded in the same direction on halfway cases. You can select several other rounding modes if they meet your needs better, see the `decimal` module documentation. – jasonharper Mar 17 '21 at 03:32
  • @jasonharper there is actually no way to set the rounding mode for a decimal using the `round` builtin function. It is set at ROUND_HALF_EVEN – user1558604 Mar 17 '21 at 03:36

1 Answers1

1

The round built-in function rounds towards the even solution when between two values.

This base round function definition is documented here: https://docs.python.org/3.7/library/functions.html#round

As the decimal package is a builtin, but not a basic type, it implements its own __round__ function, which follows the built-in standard of rounding to the even solution when between two values.

This isn't well documented, but I verified in the code itself: https://github.com/python/cpython/blob/1f0cde678406749524d11e852a16bf243cef5c5f/Lib/_pydecimal.py#L1890

There is no way to override the way the round function works for decimal objects.

Use quantize instead

The decimal package provides a function quantize which allows you to round and set the round type.

Quantize is documented here: https://docs.python.org/3/library/decimal.html#decimal.Decimal.quantize

and the round types are here: https://docs.python.org/3/library/decimal.html#rounding-modes

user1558604
  • 947
  • 6
  • 20
  • I had read the docs also, but somehow missed the detail about rounding to nearest even number. Sorry. Thanks for the reply. :) – Tanshu Mar 18 '21 at 15:55