Format number to currency

by Leandro Barbosa

JavaScript

function format1(num, currency, digits) {
  if (num % 1 !== 0) {
    digits = 2;
  }
  return currency + " " + num.toFixed(digits).replace(/./g, function(c, i, a) {
    return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
  });
}

function format2(n, currency) {
  return currency + " " + n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
}

var numbers = [1, 12, 123, 1234, 12345, 123456, 1234567, 12345.67];

document.write("<p>Format #1:</p>");
for (var i = 0; i < numbers.length; i++) {
  document.write(format1(numbers[i], "£") + "<br />");
}

document.write("<p>Format #2:</p>");
for (var i = 0; i < numbers.length; i++) {
  document.write(format2(numbers[i], "$") + "<br />");
}