[Python-Dev] Return type of round, floor, and ceil in 2.6 (original) (raw)

Tim Peters tim.peters at gmail.com
Sun Jan 6 01:32:53 CET 2008


[Mark Dickinson]

quantize is about as close as it gets. Note that it's a Decimal method as well as a Context method, so you can invoke it directly on a given decimal:

>>> Decimal("2.34567").quantize(Decimal("0.01")) Decimal("2.35")

This "reads better" in many cases if you define a constant first, like:

PENNIES = Decimal("0.01")

... [lots of code] ...

rounded = some_decimal.quantize(PENNIES)

I've also occasionally felt a need for a simple rounding function that isn't affected by context. Would others be interested in such a function being added to Decimal? I guess there are two possibly useful operations: (1) round to a particular decimal place ( e.g. nearest ten, nearest hundredth, ..) and (2) to round to a particular number of significant digits; in both cases, the user should be able to specify the desired rounding mode. And for each operation, it might also be useful to specify whether the result should be padded with zeros to the desired length or not. ( i.e. when rounding 3.399 to 3 significant places, should it produce 3.4 or 3.40?)

Any thoughts?

+1 from me. Like the 754 standard, the decimal std is trying to mandate a more-or-less minimal set of core functionality, with no concern for user interface. "Convenience functions" can be valuable additions in such cases, & I agree it's far from obvious to most how to accomplish rounding using the decimal facilities.

I think it's obvious ;-) that rounding 3.399 to 3 sig. dig. should produce 3.40.



More information about the Python-Dev mailing list