Medium: Interview Core · Problem 30 of 82

Format Money

MediumStringsPython

Write format_money(cents) that takes an integer number of cents and returns a string like "$1,234.50":

  • a dollar sign, the dollars with commas between groups of three digits, a point, and two digits of cents,
  • a negative amount puts the minus sign before the dollar sign: "-$5.00".

Use only whole-number arithmetic: the tests include amounts too big for a float to hold exactly.

Understand the problem

Look at the tools and at why floats are a poor fit.

What does f"{1234567:,}" give?

  1. "1234567"
  2. "1,234,567"
  3. "1.234.567"

The format spec , inserts commas between groups of three digits. It works for integers and floats. (_ does the same with underscores.)

What does f"{5:02d}" give?

  1. "5"
  2. "05"
  3. "5 "

02d means: an integer (d), at least 2 characters wide, padded with zeros. It is how you write the cents 05 instead of 5.

Why are cents kept as an integer and not as a float such as 12.34?

  1. Floats cannot hold decimals
  2. Floats store most decimal fractions only approximately, so sums and large values can be slightly off
  3. Integers are faster to print

A float stores binary approximations: 0.1 + 0.2 is 0.30000000000000004. For money, count in the smallest unit (cents) as an integer, which is exact. Convert to dollars only when displaying.

Write the solution

Return the formatted string.

def format_money(cents):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

How do you split a whole number of cents into dollars and cents without using division that gives a float?

Hint 2: the shape of the answer

Remember the sign, then divmod(abs(cents), 100) gives dollars and cents. Format the dollars with :, and the cents with :02d. Put the sign in front of the dollar sign.

Reflect

Solution

def format_money(cents):
    sign = "-" if cents < 0 else ""
    dollars, rest = divmod(abs(cents), 100)
    return f"{sign}${dollars:,}.{rest:02d}"

What this tests: divmod, f-string format specs (, and 02d), handling the sign separately, and why money is an integer.

The sign first: with a negative number divmod rounds the wrong way for our purpose (divmod(-5, 100) is (-1, 95)). Taking the absolute value first and adding the sign at the end avoids it.

The float version: f"${cents / 100:,.2f}" looks right and works for small amounts, but it puts the minus after the dollar sign ($-5.00) and loses digits for very large amounts.

In real code use the decimal module (Decimal) for money, or keep integers, as here.

What an interviewer might ask next: How would you add other currencies, where the number of decimals differs (Japanese yen has none)? (Pass the number of decimals, or use the decimal module.)