James James - 2 months ago 12
Javascript Question

add_commas function not working with 10000 but does 1000

Anyone have ideas why my commas are not adding now I have reached into the 10,000 but was OK in the 1,000's?

function add_commas(number) {
if (number.length > 3) {
var mod = number.length % 3;
var output = (mod > 0 ? (number.substring(0,mod)) : '');
for (i=0 ; i < Math.floor(number.length / 3); i++) {
if ((mod == 0) && (i == 0)) {
output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
} else {
output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
}
}
return (output);
} else {
return number;
}
}


I still use this for some values which are in the 1,000's so need it to still work with that but little lost what to do for the higher values?

Answer
function number_format(number, decimals, decPoint, thousandsSep) {
  number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
  var n = !isFinite(+number) ? 0 : +number
  var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
  var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
  var s = ''

  var toFixedFix = function (n, prec) {
    var k = Math.pow(10, prec)
    return '' + (Math.round(n * k) / k)
      .toFixed(prec)
  }

  // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }

  return s.join(dec)
}

number_format(100) => 100
number_format(1000) => 1,000
number_format(10000) => 10,000

Google can be your friend :) original