Created
August 14, 2012 22:58
-
-
Save rickycheers/3353745 to your computer and use it in GitHub Desktop.
A couple of functions to apply currency format to an amount number in javascript
This file contains 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
function applyFormat(value){ | |
value = typeof value == 'number' ? value.toString() : value; | |
value = value.replace(/\$|\,/g, ''); | |
if( isNaN(value) ){ | |
return '$X,XXX'; | |
} | |
var integer = value.split('.')[0]; | |
var decimal = value.split('.')[1] ? '.' + value.split('.')[1] : '' ; | |
return '$' + addCommas(integer) + decimal; | |
} | |
function addCommas(digits, complete_str){ | |
complete_str = complete_str || ''; | |
var length = digits.length; | |
if( length / 3 > 1 ){ | |
complete_str = ',' + digits.slice(length - 3, length ) + complete_str; | |
return addCommas( digits.slice(0, length - 3), complete_str ); | |
} else { | |
return digits + complete_str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment