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

std::string formatMoney(int minor) {
    
}

Worked examples

CallResult
formatMoney(123456)std::string("1,234.56")
formatMoney(0)std::string("0.00")
formatMoney(5)std::string("0.05")
formatMoney(-50)std::string("(0.50)")

Hint

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

Reference solution in C++
std::string formatMoney(int minor) {
    bool neg = minor < 0;
    int absv = neg ? -minor : minor;
    string whole = std::to_string(absv / 100);
    string cents = std::to_string(absv % 100);
    if (cents.size() < 2) cents = "0" + cents;
    string grouped;
    for (size_t i = 0; i < whole.size(); i++) {
        if (i > 0 && (whole.size() - i) % 3 == 0) grouped += ',';
        grouped += whole[i];
    }
    string body = grouped + "." + cents;
    return neg ? "(" + body + ")" : body;
}

The same problem in another language

More pricing problems in C++