Created
January 6, 2015 02:15
-
-
Save JayMc/2ab2493726e0086ce783 to your computer and use it in GitHub Desktop.
Currency formatter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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