>>> import decimal
>>> decimal.Decimal(-7) // 4
Decimal('-1') # Result rounded towards 0.
>>> -7 // 4
-2 # Result rounded towards negative infinity.
Why does the floordiv operator with a python decimal round towards 0 instead of towards negative infinity, as the floordiv operator does with all other types?
From BPO-12005 (formatting mine):
The specification on which the
decimal
module is based requires that there be a 'remainder' operation with the semantics ofDecimal
's%
operation (i.e., the result ofx % y
has the sign ofx
). However, the specification doesn't say anything about how the prescribed operations should map to language constructs.So the choice was between (1) leaving
%
forDecimal
objects unimplemented, and providing a separate 'remainder' method, or (2) mapping%
toDecimal
's remainder operation, and accepting the slight mismatch between the%
semantics forfloat
andDecimal
.Perhaps the wrong choice was made. But it's there now, and to me it's not so obviously wrong that it's worth the upheaval of deprecating
%
forDecimal
objects.— Mark Dickinson (May 5, 2011)
The post above is about %
, but this also applies to //
.