Skip to main content

Given an amount of money as a float, format it as a string.

/**
 * Given an amount of money as a float, format it as a string.
 *
 * example:
 *   formatMoney(120.23); // $120.23
 *
 * @param  {number} amount The floating point amount.
 * @return {string}
 */
function formatMoney(amount) {
  var remaining = amount - ~~amount,
    string = '' + ~~amount,
    length = string.length,
    places = 0;

  while (--length) {
    places += 1;
    // At every third position we want to insert a comma
    if (places % 3 === 0) {
      string = string.substr(0, length) + ',' + string.substr(length);
    }
  }

  return '$' + string + remaining.toFixed(2).slice(1);
}