Skip to content

Instantly share code, notes, and snippets.

@klarstil
Created July 2, 2013 07:28
Show Gist options
  • Save klarstil/5907372 to your computer and use it in GitHub Desktop.
Save klarstil/5907372 to your computer and use it in GitHub Desktop.
;(function($) {
/**
* Formats a given number (or number as a string)
*
* @param {Number|String} num
* @param {Object} [userOpts] User configuration
* @returns {String|Boolean}
*/
var formatNumber = function(num, userOpts) {
var defaults = {
decimals: 2,
prefix: '',
suffix: '',
separator: {
decimal: ',',
thousand: '.'
}
}, opts;
userOpts = userOpts || {};
opts = $.extend({}, defaults, userOpts);
// Cast the string to a number
if(typeof(num) === 'string') {
num = 1 * num;
}
if(!isFinite(num)) {
return false;
}
num = num.toFixed(opts.decimals);
// Replace the dot
num = num.replace(/\./, opts.separator.decimal);
// Set the thousand separator
num = num.replace(/\B(?=(\d{3})+(?!\d))/g, opts.separator.thousand);
num = opts.prefix + num + opts.suffix;
return num;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment