Drill

ProblemsPython › pricing

Format money for a receipt

mediumpricingPython

The receipt printer takes a plain string. Amounts arrive in minor units and have to come out grouped and signed the way finance expects.

format_money(minor: int) → string

Solve it in the editor →

Where you start

def format_money(minor: int) -> str:
    

Worked examples

CallResult
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

The same problem in another language

More pricing problems in Python