> 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4