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).
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.
Where you start
public string FormatMoney(int minor) {
}
Worked examples
| Call | Result |
|---|---|
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;
}