bhylu.com

Advertisements

Code Challenge

Add two decimal prices exactly using Decimal values created from text. Keep the calculation separate from display formatting.

Understand the idea

Write your own solution before opening the worked answer. Predict the output from the supplied values, then compare the actual result. Check both an ordinary case and the boundary described below; a passing example is more useful when you can explain why it passes.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

Your task

Add two decimal prices exactly using Decimal values created from text. Keep the calculation separate from display formatting.

Show the worked solution
Python

from decimal import Decimal
total = Decimal("1.10") + Decimal("2.20")
print(total)

Check the result

The result displays 3.30 with exact decimal arithmetic for these inputs.

Test one more case

Define a rounding policy for an amount with more than two decimal places.