Python course Lesson 5 of 6

Python from zero: money is a Decimal

A price is a Decimal made from a string, not a float. Three americanos at 4.10 print 12.30, and the total equals Decimal("12.30").

Zoe is one of GoByte's characters. This post was drafted by AI agents in Zoe's voice, then fact checked, run and edited by the GoByte team.

Back to top

4.10 written as a float is not exactly 4.10. The binary fraction is close, and three americanos at that price can print a tail of extra digits. Decimal stores the number you wrote. Build it from a string so the digits are the digits. Three times 4.10 is 12.30, and the program checks that.

Decimal keeps the base-ten number#

0.1 + 0.2 is not 0.3 in binary floating point, because those decimals do not have a finite binary expansion. Decimal("4.10") parses the base-ten digits in the string, so the value is exactly 410 hundredths. Multiplying by the int 3 scales it to 1230 hundredths, which prints as 12.30. Constructing Decimal from a float would capture the float's error first. The string is the input that has not been rounded yet. The comparison against Decimal("12.30") is exact, and it prints True.

Three americanos stay in base ten
  1. priceDecimal4.10
  2. totalDecimal12.30
from decimal import Decimal

price = Decimal("4.10")
total = price * 3
print(total)
print(total == Decimal("12.30"))
12.30
True

The string is the source of the digits#

Decimal("4.10") is four dollars and ten cents, the price of one americano. Decimal(4.10) would capture the float's inexact value, which defeats the type. The quotes are the tip. price * 3 is still a Decimal, and it prints 12.30. The second line is True, so the total for three is the decimal you expect, not a near miss.

You can add Decimals to Decimals. Adding a Decimal to a float raises TypeError. Keep the money in one type for the whole calculation. Format it when you show it to a person, not in the middle of the sum.

Cents are the other honest choice#

An int of cents, 410, also avoids the float. The earlier lessons used 450 cents for a latte for that reason. Pick one. Decimal is the right tool when the input arrives as "4.10". An int is the right tool when the input arrives as a count of cents. The next lesson calls a method without caring which class the object came from.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.