Drill

ProblemsJava › pricing

Format money for a receipt

mediumpricingStringsMathJava

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

Java 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

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 Java
String formatMoney(int minor) {
    boolean neg = minor < 0;
    int abs = Math.abs(minor);
    String whole = String.valueOf(abs / 100);
    String cents = String.valueOf(abs % 100);
    if (cents.length() < 2) cents = "0" + cents;
    StringBuilder g = new StringBuilder();
    for (int i = 0; i < whole.length(); i++) {
        if (i > 0 && (whole.length() - i) % 3 == 0) g.append(',');
        g.append(whole.charAt(i));
    }
    String body = g + "." + cents;
    return neg ? "(" + body + ")" : body;
}

The same problem in another language

More pricing problems in Java