Skip to content

Instantly share code, notes, and snippets.

@ironboy
Created October 23, 2015 10:08
Show Gist options
  • Save ironboy/1241ce9f86ae0879ea3a to your computer and use it in GitHub Desktop.
Save ironboy/1241ce9f86ae0879ea3a to your computer and use it in GitHub Desktop.
// options object example
/*
{
decimals:2,
decimalSign:",",
thousandSep: " ",
currency:"SEK"
}
*/
Number.prototype.toCurrency = function(options){
var o = options, d = Math.pow(10,o.decimals), n = Math.round(d*this)/d, n2 = '';
var dec = (n +'').split('.')[1] || '0';
while(dec.length < o.decimals){dec += '0';}
((o.decimals ? Math.floor(n) : Math.round(n)) + '').split('').reverse().forEach(
function(x,i){
n2 = (i%3 ==2 ? ' ' : '') + x + n2;
}
);
return n2 + (o.decimals ? options.decimalSign + dec : '') +
(options.currency ? ' ' + options.currency : '');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment