Skip to content

Instantly share code, notes, and snippets.

@fredyfx
Created February 16, 2017 20:19
Show Gist options
  • Save fredyfx/b81feccddb294679bce1fae37661f352 to your computer and use it in GitHub Desktop.
Save fredyfx/b81feccddb294679bce1fae37661f352 to your computer and use it in GitHub Desktop.
function format1(n, currency) {
return currency + " " + n.toFixed(2).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 />");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment