Skip to content

Instantly share code, notes, and snippets.

@vishwanatharondekar
Created April 19, 2016 16:36
Show Gist options
  • Save vishwanatharondekar/25582786ed936691a59c6240f7bf9c1c to your computer and use it in GitHub Desktop.
Save vishwanatharondekar/25582786ed936691a59c6240f7bf9c1c to your computer and use it in GitHub Desktop.
Sum function in javascript which handles nan and decimal points correctly
function sum(){
var args = Array.prototype.slice.call(arguments);
var total = 0;
var highestDecimalPoints = 0;
var sanitizedArray = [];
args.forEach(function(no){
if(!isNaN(no)){
//If no is decimal
if(no % 1 > 0){
var noStr = no.toString();
var decimalPoints = noStr.length - 1 - noStr.indexOf('.');
highestDecimalPoints = decimalPoints > highestDecimalPoints ? decimalPoints : highestDecimalPoints;
}
sanitizedArray.push(no)
}
});
var multiplier = 1;
for(var i=0; i < highestDecimalPoints; i++){
multiplier = multiplier * 10;
}
for(var index in sanitizedArray){
total += sanitizedArray[index] * multiplier;
}
total = total / multiplier;
return total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment