I have a requirement to validate the sum of the elements of my array net to zero. The array could contain positive or negative values. The array elements are 1164.44,-2919.42,2500.59,-5197.15,4451.54 My code without using toFixed is
var v_total=0;
var v;
var varray = document.getElementsByName('f02');
for (var i = 0; i < varray.length; i++)
{
v = (isNaN(parseFloat(varray[i].value)))?0:varray[i].value;
v_total = parseFloat(cv_total) + parseFloat(v);
}
v_total = (isNaN(cv_total))?0:cv_total;
which results with the sum 9.094947017729282e-13 If I add it using a calc, it does net to zero Searched the forum and understand that it is the behaviour of floating numbers. Despite using toFixed, I am unable to get the sum zero . Also the number of digits after the decimal could vary and is not always 2 Request any advice on how to workaround this
Thanks
You can use reduce() and toPrecision():
var arr =[1164.44,-2919.4204,2500.5904,-5197.151,4451.541];
var result = arr.reduce(function(a, b){ return +a.toPrecision(15) + +b.toPrecision(15) });
alert(result);