[issue32908] decimal ROUND_HALF_UP not according to spec for 9.95 to 10.0

Mark Dickinson report at bugs.python.org
Thu Feb 22 05:12:18 EST 2018


Mark Dickinson <dickinsm at gmail.com> added the comment:

This isn't a bug. When you do `Decimal(9.95)`, you're converting the binary floating-point number `9.95` to a `Decimal` instance. The conversion is performed exactly, with no change in the value. But the *input* to the conversion, the float `9.95` can't be stored exactly in IEEE 754 binary64 format, so what you end up with is something very slightly smaller.

>>> from decimal import Decimal
>>> Decimal(9.95)
Decimal('9.949999999999999289457264239899814128875732421875')

That's the reason that it rounds down.

Good practice is to create your Decimal instances from strings rather than floats.

>>> Decimal(9.95).quantize(Decimal('1.1'),ROUND_HALF_UP)
Decimal('9.9')
>>> Decimal('9.95').quantize(Decimal('1.1'),ROUND_HALF_UP)
Decimal('10.0')

----------
nosy: +mark.dickinson
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32908>
_______________________________________


More information about the Python-bugs-list mailing list