Editor

Money With a Currency

#338 · Classes · Intermediate · 85 XP · about 18 min

Floats cannot store most amounts exactly (0.1 + 0.2 is 0.30000000000000004), so programs that handle money count whole cents instead. Build a Money class that does this and also keeps track of the currency.

  • Money(cents, currency) stores a whole number of cents and a currency code such as 'USD', as the attributes cents and currency.
  • Money.from_string(text) is a class method that reads text like '12.50 USD' or '-0.05 EUR': an optional minus sign, digits, a dot, exactly two digits, a space and the currency code. It returns the matching Money.
  • a + b and a - b return a new Money. If the two currencies differ, they raise ValueError.
  • 0 + m returns m, so the built-in sum() works on a list of Money.
  • a == b is True when both the cents and the currency are equal. Comparing with something that is not Money gives False.
  • repr(m) returns the amount with exactly two decimals, a space and the currency, for example 12.50 USD, -0.05 EUR or 0.00 GBP.

Examples

lunch = Money.from_string('12.50 USD')
coffee = Money(375, 'USD')
lunch + coffee                 # 16.25 USD
coffee - lunch                 # -8.75 USD
sum([lunch, coffee, coffee])   # 20.00 USD
Money(5, 'EUR') == Money.from_string('0.05 EUR')    # True
lunch + Money(100, 'EUR')      # raises ValueError

Constraints

  • Amounts can be negative and as large as you like

Note

Negative amounts are the tricky part, both when reading them and when writing them.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.