Drill

ProblemsJavaScript › pricing

Format money for a receipt

mediumpricingJavaScript

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

Solve it in the editor →

Where you start

function formatMoney(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 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;
}

The same problem in another language

More pricing problems in JavaScript