shuuuuun
1/14/2016 - 3:21 AM

小数をdecimalLengthで切り捨てor四捨五入して、数値をカンマ区切りにするformatNumber関数

小数をdecimalLengthで切り捨てor四捨五入して、数値をカンマ区切りにするformatNumber関数

function formatNumber(number, decimalLength) {
  // 小数をdecimalLengthで切り捨てて、数値をカンマ区切りにする
  decimalLength = decimalLength || 0;
  var str = number.toString().split(".");
  var base = str[0].replace(/(?!^)(?=(\d{3})+$)/g,",");
  var decimal = (str[1]) ? str[1].slice(0, decimalLength) : Array(decimalLength + 1).join("0");
  var result = (!decimalLength) ? base : base + "." + decimal;
  return result;
}

// ex. -----
formatNumber(12345); // => "12,345"
formatNumber(12345.6789, 2); // => "12,345.67"
formatNumber(12345.6789, 3); // => "12,345.678"
function formatNumber(number, decimalLength) {
  // 小数をdecimalLengthに四捨五入して、数値をカンマ区切りにする
  decimalLength = decimalLength || 0;
  var dimension = Math.pow(10, decimalLength);
  var roundNum = Math.round(number * dimension) / dimension;
  if (number < 0) roundNum *= -1;
  var str = roundNum.toString().split(".");
  var base = str[0].replace(/(?!^)(?=(\d{3})+$)/g,",");
  var decimal = ((str[1] || "") + Array(decimalLength + 1).join("0")).slice(0, decimalLength);
  var result = (!decimalLength) ? base : base + "." + decimal;
  if (number < 0) result = "-" + result;
  return result;
}

// ex. -----
formatNumber(12345); // => "12,345"
formatNumber(12345.6789, 2); // => "12,345.68"
formatNumber(12345.6789, 3); // => "12,345.679"
formatNumber(12345.6999, 3); // => "12,345.700"