> Q. I'm writing a fixed-point application to two decimal places.
> Some inputs have many places and needed to be rounded. Others
> are not supposed to have excess digits and need to be validated.
> What methods should I use?
>
> A. The quantize() method rounds to a fixed number of decimal
> places. If the Inexact trap is set, it is also useful for
> validation:
>
> >>> TWOPLACES = Decimal(10) ** -2
> >>> # Round to two places
> >>> Decimal("3.214").quantize(TWOPLACES)
> Decimal("3.21")
> >>> # Validate that a number does not exceed two places
> >>> Decimal("3.21").quantize(TWOPLACES,
> context=Context(traps=[Inexact]))
> Decimal("3.21")
I think an example of what happens when it does exceed two places would make
this example clearer. For example, adding this to the end of that:
>>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
[...]
Inexact: Changed in rounding
=Tony.Meyer
_______________________________________________
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com