Code Explanation:
๐น 1. Importing Decimal
from decimal import Decimal
✅ Explanation
Decimal is imported from Python's decimal module.
It is used for high-precision decimal arithmetic.
Unlike float, Decimal stores decimal numbers exactly, avoiding rounding errors.
Think of it like a scientific calculator that performs very accurate decimal calculations.
Float
↓
Approximate Value
Decimal
↓
Exact Value
๐น 2. Creating the First Decimal Object
x = Decimal("1.10")
✅ Explanation
A Decimal object is created with the value "1.10".
Notice:
"1.10"
is a string, not a float.
Python stores the value exactly as:
1.10
Memory:
x
↓
Decimal('1.10')
๐น 3. Why Use a String?
Decimal("1.10")
✅ Explanation
Using a string prevents floating-point precision errors.
For example:
0.1 + 0.2
Output:
0.30000000000000004
But with Decimal:
Decimal("0.1") + Decimal("0.2")
Output:
0.3
This is why strings are recommended when creating Decimal objects.
๐น 4. Creating the Second Decimal Object
y = Decimal("2.20")
✅ Explanation
Another Decimal object is created.
Memory:
y
↓
Decimal('2.20')
Current memory:
x
↓
1.10
y
↓
2.20
๐น 5. Performing Addition
x + y
✅ Explanation
Python adds the two Decimal values.
Calculation:
1.10
+
2.20
↓
3.30
Unlike float, no precision is lost.
Result:
Decimal('3.30')
๐น 6. Preserving Trailing Zeros
✅ Explanation
One important feature of Decimal is that it preserves trailing zeros.
Example:
1.10
+
2.20
↓
3.30
Notice:
Python prints:
3.30
not
3.3
This is useful in:
Banking
Finance
Accounting
Scientific calculations
where decimal precision matters.
๐น 7. Printing the Result
print(x + y)
✅ Explanation
Python prints the result of the addition.
Output:
3.30
๐ฏ Final Output
3.30

0 Comments:
Post a Comment