'use strict';

/**
 * 格式化金钱，隔三位以逗号隔开
 * @param {*} amount
 * @param {*} digit
 * @returns {string}
 *
 * formatMoney();      // => '0.00'
 * formatMoney(99, 1); // => '99.0'
 * formatMoney(1999);  // => '1,999.00'
 * formatMoney(100000000);  // => '100,000,000.00'
 */
function formatMoney(amount, digit) {
  amount = amount || 0;
  if (digit === undefined) digit = 2;
  var amountArr = String(amount.toFixed(digit)).split('.');
  var _int = amountArr[0];
  var decimal = amountArr[1] || '';
  var spNum = Math.floor(_int.length / 3);
  var spIdx = _int.length % 3;

  var spStr = _int.substr(0, spIdx);

  var i = -1;

  while (++i < spNum) {
    spStr += i === 0 && (spStr === '-' || !spStr) ? _int.substr(spIdx, 3) : ",".concat(_int.substr(spIdx, 3));
    spIdx += 3;
  }

  return decimal ? "".concat(spStr, ".").concat(decimal) : spStr;
}

module.exports = formatMoney;
