Drill

ProblemsC# › pricing

Format money for a receipt

mediumpricingStringsMathC#

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

FormatMoney(minor: int) → string

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public string FormatMoney(int minor) {
    
}

Worked examples

CallResult
FormatMoney(123456)"1,234.56"
FormatMoney(0)"0.00"
FormatMoney(5)"0.05"
FormatMoney(-50)"(0.50)"

Hint

Split into whole and remainder first, build the grouped whole part, then glue on the sign.

Reference solution in C#
public string FormatMoney(int minor) {
    bool neg = minor < 0;
    int abs = Math.Abs(minor);
    string whole = (abs / 100).ToString();
    string cents = (abs % 100).ToString().PadLeft(2, '0');
    var g = new StringBuilder();
    for (int i = 0; i < whole.Length; i++) {
        if (i > 0 && (whole.Length - i) % 3 == 0) g.Append(',');
        g.Append(whole[i]);
    }
    string body = g.ToString() + "." + cents;
    return neg ? "(" + body + ")" : body;
}

The same problem in another language

More pricing problems in C#