This returns the expected result:
function add(){ // Initialize output and "length" properties var length = 0; var output = 0; // Loop through all arguments supplied to this function (So: 1,4,6 in case of add(1,4,6);) for(var i = 0; i < arguments.length; i++){ // If the current argument length as string is longer than the previous one (or greater than 0 in case of the first argument)) if(arguments[0].toString().length > length){ // Set the current length to the argument length (+1 is to account for the decimal point taking 1 character.) length = arguments[0].toString().length +1; } // Add the current character to the output with a precision specified by the longest argument. output = parseFloat((output+arguments[i]).toPrecision(length)); } // Do whatever you with with the result, here. Usually, you'd 'return output;' console.log(output); } add(); // Returns 0 add(1,2,3); // Returns 6 add(1.01,2.01,3.03); // Returns 6.05 add(1.01,2.0213,3.3333); // Returns 6.3646 add(11.01,2.0213,31.3333); // Returns 44.3646
parseFloat even gets rid of parseFloat zero for you.
This function takes as many numbers as you want, and then adds them together, taking the string length of the numbers into account when adding them. The precision used in the addition is dynamically modified to match the โcurrently addedโ argument length.
Fiddle
source share