Modulo operation on negative decimal python.Decimal and positive int

With simple ints:

>>> -45 % 360
315

Whereas with decimal.Decimal:

>>> from decimal import Decimal
>>> Decimal('-45') % 360
Decimal('-45')

I expect to receive Decimal('315').

Is there a reason for this? Is there a way to achieve consistent behavior (without patching decimal.Decimal)? (I did not change the context and cannot find how it could be changed to solve this situation).

+4
source share
1 answer

After a lengthy search (because searching on "%", "mod", "modulo", etc. gives a thousand results), I finally found that, surprisingly, this is provided for :

. % , - , :

>>> (-7) % 4
1
>>> Decimal(-7) % Decimal(4)
Decimal('-3')

, , .

+3

Source: https://habr.com/ru/post/1692431/


All Articles