I have a double var
public double votes(){
double votexp = 0;
for(Elettore e:docenti.values()){
if(e.getVoto()==true) //everytime this is true increment by 1
{
votexp+=1.0;
}
}
for(Elettore e:studenti.values()){
if(e.getVoto()==true) //everytime this is true increment by 0.2
{
votexp+=0.2;
}
}
for(Elettore e:pta.values()){
if(e.getVoto()==true) //everytime this is true increment by 0.2
{
votexp+=0.2;
}
}
return votexp;
}
In my case the variable shoud be incremented to 2.6 but votexp returns 2.6000000000000005
how can i fix this by using the same double var and return a double precision number ?
You are accumulating a rounding error. The simplest thing to do is to use an
long(orintand only use a double at the end. (Or a BigDecimal and double at the end, but this is overly complicated)prints
As the Double.toString() “knows” values can be imprecise, it will do a small amount of rounding. This rounding is limited so the result of operating on two
doublecan have an error too large to hide. If you round your last result correctly, the error will be small enough it won’t cause a problem.