Skip to content

Instantly share code, notes, and snippets.

@fliptopbox
Created June 12, 2013 13:32
Show Gist options
  • Save fliptopbox/5765263 to your computer and use it in GitHub Desktop.
Save fliptopbox/5765263 to your computer and use it in GitHub Desktop.
Javascript Number.toCurrency() to convert INT 1234567 to CURRENCY £1,2345.67
/*
@fliptopbox
Format a number as a currency.
eg. 12345.67 = £12,345.67
usage examples:
(1234567.899).toCurrency(); // 1,234,567
(1234567.999).toCurrency(0); // 1,234,567
(1234567.999).toCurrency(2); // 1,234,568.00
(1234567.999).toCurrency(2, '£'); // £1,234,568.00
(1234567.999).toCurrency(2, '£', ':'); // £1:234:568.00
*/
if(!Number.toCurrency) {
Number.prototype.toCurrency = function (decimals, prefix, kdelim) {
decimals = typeof decimals === 'number' ? Math.min(decimals, 2) : 0;
prefix = prefix || ''; // the currency prefix eg. '$'
kdelim = kdelim || ','; // thousand delimininator eg. ','
var value = this,
valueAsInt = parseInt(value, 10),
valueAsFixed = value.toFixed(decimals),
stringValue = String(decimals === 0 ? valueAsInt : valueAsFixed)
rex = new RegExp(kdelim + '$');
return (
prefix + stringValue.split('').reverse().join('')
.replace(/(\d{3})/g, function(m,a) { return a + kdelim}).replace(rex, '')
.split('').reverse().join('')
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment