Created
July 2, 2013 07:28
-
-
Save klarstil/5907372 to your computer and use it in GitHub Desktop.
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($) { | |
/** | |
* 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