Problems › JavaScript › pricing
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
Where you start
function formatMoney(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 JavaScript
function formatMoney(minor) {
const neg = minor < 0;
const abs = Math.abs(minor);
const whole = String(Math.floor(abs / 100));
const cents = String(abs % 100).padStart(2, '0');
let grouped = '';
for (let i = 0; i < whole.length; i++) {
if (i > 0 && (whole.length - i) % 3 === 0) grouped += ',';
grouped += whole[i];
}
const body = grouped + '.' + cents;
return neg ? '(' + body + ')' : body;
}