Skip to content

Instantly share code, notes, and snippets.

@ducdhm
Last active September 27, 2016 03:19
Show Gist options
  • Save ducdhm/9105925 to your computer and use it in GitHub Desktop.
Save ducdhm/9105925 to your computer and use it in GitHub Desktop.
Add multiple floats as well as numbers
/**
* Bob Math utilities
* @author: ducdhm
* @created: Tue, Feb 11th, 2014 (GTM+7)
*/
(function(Math) {
/**
* Find the number of decimal places
* @method findDec
* @param {Float|Number} dec
* @return {Number}
*/
var findDec = function(dec) {
dec = '' + dec;
if (dec.indexOf('.') === -1) {
return 0;
} else {
dec = dec.split('.')[1];
return dec.length;
}
};
/**
* Find the greatest number of decimal places
* @method findFixed
* @param {Float|Number} dec
* @return {Number}
*/
var findFixed = function() {
var fixed = [];
for (var i = 0; i < arguments.length; i++) {
fixed.push(findDec(arguments[i]));
}
// log(fixed);
return Math.max.apply(this, fixed)
};
/**
* Calculate total
* @method findFixed
* @param {Float|Number}
* @return {Float|Number}
*/
var calculate = function() {
var total = 0;
for (var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
/**
* Add float number
* @method addNumber
* @param {Float|Number}
* @return {Float|Number}
*/
Math.addNumber = function() {
//Determine the greatest number of decimal places
var fixed = findFixed.apply(this, arguments);
var total = calculate.apply(this, arguments);
//do the math then do a toFixed, could do a toPrecision also
return +total.toFixed(fixed);
}
})(Math);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment