It looks like you’re using the Decimal objects from the decimal module, which is great for handling fixed-point arithmetic. The Decimal class has a quantize() method that can round a number to a fixed number of decimal places, which is exactly what you need for formatting values like money.
Here’s a simple example:
from decimal import Decimal, Context, Inexact
# Define the precision
TWOPLACES = Decimal(10) ** -2 # This represents 0.01
# Round to two places
formatted_decimal = Decimal('3.214').quantize(TWOPLACES)
print(formatted_decimal) # Outputs: 3.21
For validating that a number doesn't exceed two decimal places, you can use the Inexact trap, which will raise an exception if the number has more than two decimal places:
try:
Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
except Inexact:
print("Number exceeds two decimal places.")
Additionally, to maintain two decimal places across your application, you can rely on string conversion after rounding:
formatted_string = str(Decimal('10.00'))
print(formatted_string) # Outputs: 10.00