Format money for a receipt
The receipt printer takes a plain string. Amounts arrive in minor units and have to come out grouped and signed the way finance expects.
- Always two decimal places.
- Group the whole part in threes with commas: 123456 becomes 1,234.56.
- Negatives are wrapped in parentheses with no minus sign, so -50 becomes (0.50).
format_money(minor: int) → string
Where you start
def format_money(minor: int) -> str:
Worked examples
| Call | Result |
|---|---|
format_money(123456) | "1,234.56" |
format_money(0) | "0.00" |
format_money(5) | "0.05" |
format_money(-50) | "(0.50)" |
Hint
Split into whole and remainder first, build the grouped whole part, then glue on the sign.
Reference solution in Python
def format_money(minor: int) -> str:
neg = minor < 0
abs_v = abs(minor)
whole = str(abs_v // 100)
cents = str(abs_v % 100).rjust(2, '0')
grouped = ''
for i, ch in enumerate(whole):
if i > 0 and (len(whole) - i) % 3 == 0:
grouped += ','
grouped += ch
body = grouped + '.' + cents
return '(' + body + ')' if neg else body