[英]Javascript Validate Sum of array elements net to zero
I have a requirement to validate the sum of the elements of my array net to zero. 我需要将数组net的元素总和验证为零。 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
数组元素是1164.44,-2919.42,2500.59,-5197.15,4451.54我的代码没有使用toFixed是
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. 得出的总和为9.094947017729282e-13如果我使用calc将其相加,则它的净值为零。搜索了论坛并了解这是浮点数的行为。 Despite using toFixed, I am unable to get the sum zero .
尽管使用了toFixed,但我无法获得总和零。 Also the number of digits after the decimal could vary and is not always 2 Request any advice on how to workaround this
另外,小数点后的位数可能会有所不同,并且并不总是2。
Thanks 谢谢
This works fine, what seems to be the problem? 这工作正常,似乎是什么问题?
var n=[1164.44,-2919.42,2500.59,-5197.15,4451.54];
s=n.reduce(function(x,y) {
return parseFloat((x+y).toFixed(2));
});
console.log(s);
JSFiddle here: http://jsfiddle.net/91g4qb0z/ JSFiddle在这里: http : //jsfiddle.net/91g4qb0z/
You can use reduce() and toPrecision(): 您可以使用reduce()和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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.