Skip to content

Instantly share code, notes, and snippets.

@rickycheers
Created August 14, 2012 22:58
Show Gist options
  • Save rickycheers/3353745 to your computer and use it in GitHub Desktop.
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
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