Created
April 19, 2016 16:36
-
-
Save vishwanatharondekar/25582786ed936691a59c6240f7bf9c1c to your computer and use it in GitHub Desktop.
Sum function in javascript which handles nan and decimal points correctly
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 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