Decimals Module

In this exercise, we used the decimal module’s Decimal data type to control how many decimal places a number has after two numbers are added/multiplied together. Here is the code I used for this exercise:

# Import Decimal below:
from decimal import Decimal

# Fix the floating point math below:
two_decimal_points = Decimal('0.2') + Decimal('0.69')
print(two_decimal_points)

four_decimal_points = Decimal('0.53') * Decimal('0.65')
print(four_decimal_points)

I don’t understand how using Decimal in the two_decimal_points expression results in a float with two decimal places, while the four_decimal_points expression results in a float four decimal places. It appears as though we’re doing the same thing to both expressions, so how are they resulting in different decimal places??

decimal behaves like beginners sometimes mistakenly expect float to behave.
so if you do that multiplication yourself as if it was in a grade school math book, how many decimals do you get?

also see the Decimal module documentation which mentions this

3 Likes

@ionatan got it, thanks!

I have a general question about the Decimal module. Why do we have to add quotations for the number if it’s an integer and not a string?

Fix the floating point math below:

two_decimal_points = Decimal(‘0.2’) + Decimal(‘0.69’)
print(two_decimal_points)

Thank you

It is a way to guarantee they are stored in their fixed form, not as binary representations. They speak of this in the documentation…

decimal — Decimal fixed point and floating point arithmetic — Python 3.12.0 documentation