Skip to content

Instantly share code, notes, and snippets.

@acauamontiel
Last active August 29, 2015 14:03
Show Gist options
  • Save acauamontiel/0530cb70687f07896c04 to your computer and use it in GitHub Desktop.
Save acauamontiel/0530cb70687f07896c04 to your computer and use it in GitHub Desktop.
Useful mathematical methods
/**
* The Math.between() function returns only numbers between the smallest and largest number
* @example
* // returns 2
* Math.between(2, 1, 3);
* @example
* //returns 3
* Math.between(4, 1, 3);
* @example
* //returns 1
* Math.between(0, 1, 3);
* @param {Number} num - Number to be calculated
* @param {Number} min - The smallest number to be returned
* @param {Number} max - The largest number to be returned
* @returns {Number} Filtered number
*/
Math.between = function (num, min, max) {
return Math.min(Math.max(num, min), max);
};
/**
* Calculates the percentage of a number compared to another
* @example
* // returns 50
* Math.percentage(2, 4);
* @example
* //returns 28.5714
* Math.percentage(2,7,4);
* @param {Number} num - Number to be compared
* @param {Number} total - Total number
* @param {Number} decimal - Number of decimal places
* @returns {Number} Calculated percentage
*/
Math.percentage = function(num, total, decimal) {
return parseFloat(((num * 100) / total).toFixed(decimal || 2));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment