user2239318
user2239318

Reputation: 2784

Python decimal ROUND_UP InvalidOperation

Why happen this conversion to a number with 2 decimals?

x = 369.69

y=decimal.Decimal(x)
Decimal('369.68999999999999772626324556767940521240234375')

even if I've declared

getcontext().prec = 2       

?

Then why if I try to get the roundup to get 370.00:

y.quantize(decimal.Decimal('0.01'),rounding=decimal.ROUND_UP)

end up with this error:

InvalidOperation: quantize result has too many digits for current context quantize result has too many digits for current context

Upvotes: 1

Views: 1444

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308196

When you create a Decimal object, the prec is ignored. From the documentation:

The significance of a new Decimal is determined solely by the number of digits input. Context precision and rounding only come into play during arithmetic operations.

The error you're getting in the quantize is because the number of digits in the result is greater than the set precision. prec sets the total number of digits, not the digits after the decimal point.

>>> y = decimal.Decimal(69.69)
>>> y
Decimal('69.68999999999999772626324556767940521240234375')
>>> y.quantize(decimal.Decimal('1'), rounding=decimal.ROUND_UP)
Decimal('70')

Upvotes: -1

Tom Dalton
Tom Dalton

Reputation: 6190

The issue is that x is a float, and so you've lost precision as soon as you assign to x. If you want to work round this, you could make x a string "369.69". A Decimal built from a string will have the exact precision.

Upvotes: 4

Related Questions