[Python-3000] Rounding in Py3k

Ron Adam rrr at ronadam.com
Fri Aug 4 07:33:01 CEST 2006

Greg Ewing wrote:
> Nick Coghlan wrote:
>> Would it be worthwhile to design a common rounding mechanism that can be used 
>> to cleanly round values to the built in floating point type, as well as being 
>> able to access the different rounding modes for decimal instances?
> Sounds like a job for a new protocol, such as __round__(self, mode, places).
> --
> Greg

Yes I agree.  And viewing this in the larger sense of how it works with 
all numeric types is better than just sticking a function into the math 
module I think.  (Although that might end up the way to do it.)

Nicks proposal adds a private method to each of the types for each mode, 
which I think clutters things up a bit, but his method does create a 
single interface to them which is nice.

I'm still not sure why "__round__" should be preferred in place of 
"round" as a method name.  There isn't an operator associated to 
rounding so wouldn't the method name not have underscores?

I think rounding any type should return that same type.  For example:

     def round(n, places, mode='half-down'):
        return n.round(places, mode)

     round(i, 2)    -> integer, unchanged value
     round(i)       -> integer, precision == 0
     round(i, -2)   -> integer

     round(f, 2)    -> float
     round(f)       -> float,   precision == 0
     round(f, -2)   -> float

     round(d, 2)    -> decimal
     round(d)       -> decimal,  precision == max (*)
     round(d, -2)   -> decimal

(*) The default decimal rounding behavior is not the same as the default 
builtin round behavior.  Should one be changed to match the other?

Calling the desired types method directly could be a good way to handle 
getting an integer when a float is given.  It's explicit.

     int.round(f, 2)  ->  integer
     int.round(f)     ->  integer
     int.round(f -2)  ->  integer

Or if you prefer...


Having modes seems to me to be the best way not to clutter the namespace 
although sometimes that seems like it's not an issue, and sometimes it 
seems like it is.

Here's the list of java rounding modes for comparison. It's nearly 
identical to the ones in Decimal.



More information about the Python-3000 mailing list