Skip to content

Instantly share code, notes, and snippets.

@JayMc
Created January 6, 2015 02:15
Show Gist options
  • Save JayMc/2ab2493726e0086ce783 to your computer and use it in GitHub Desktop.
Save JayMc/2ab2493726e0086ce783 to your computer and use it in GitHub Desktop.
Currency formatter
//As Node doesn't have any internationalization included .toLocaleString() wont work.
//either install intl (npm install intl) or use a function like below
_toMoney = function(number) {
var integer = number.toString().split('.')[0];
var decimal = _getDecimal(number);
integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if( !decimal || !decimal.length ) {
decimal = "00";
} else if ( decimal.length === 1) {
decimal += '0';
} else if ( decimal.length > 2 ) {
decimal = decimal.substr(0, 2);
}
return '$' + integer + '.' + decimal;
};
_getDecimal = function(number) {
var n = Math.abs(number);
var dec = (n - Math.floor(n)).toString();
if( dec.split('.').length ) {
return dec.split('.')[1];
} else return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment