Question about floating point

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 31 19:34:26 EDT 2018


On Fri, 31 Aug 2018 18:45:16 +1200, Gregory Ewing wrote:

> Steven D'Aprano wrote:
>> The right way is to
>> set the rounding mode at the start of your application, and then let
>> the Decimal type round each calculation that needs rounding.
> 
> It's not clear what you mean by "rounding mode" here. If you mean
> whether it's up/down/even/whatever, then yes, you can probably set that
> as a default and leave it.

I mean the rounding mode :-)

https://docs.python.org/3/library/decimal.html#rounding-modes


> However, as far as I can see, Decimal doesn't provide a way of setting a
> default number of decimal places to which results are rounded. You can
> set a default *precision*, but that's not the same thing.

Indeed it is not. That's a very good point, and I had completely 
forgotten about it! Thank you.

The quantize method is intended for the use-case we are discussing, to 
round values to a fixed number of decimal places. The Decimal FAQs 
mention that:

https://docs.python.org/3/library/decimal.html#decimal-faq

I think this is a good use-case for subclassing Decimal as a Money class.

[...]
> I don't think this is a bad thing, because often you don't want to use
> the same number of places for everything, For example, people dealing
> with high-volume low-value goods often calculate with unit prices having
> more than 2 decimal places. In those kinds of situations, you need to
> know exactly what you're doing every step of the way.

As opposed to anyone else calculating with money?




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list