0

I have this code:

try {
    Ciocco_V.tot = Double.parseDouble(Et444Tot.getText().toString());
} catch (NumberFormatException e) {
    e.printStackTrace();
}

try {
    Ciocco_V.burro = Double.parseDouble(Et111Burro.getText().toString()); 
} catch (NumberFormatException e) {
    e.printStackTrace();
}

try {
    Ciocco_V.fibra = Double.parseDouble(Et222Fibra.getText().toString());
} catch (NumberFormatException e) {
    e.printStackTrace();
}

and inside the edittex there are this number:

44.2(burro) and 40.6(fibra) 84.8(tot)

if (((Ciocco_V.burro + Ciocco_V.fibra) != Ciocco_V.tot ) {
    //fail condition
} else {
   // correct
}

if I inspect the condition Ciocco_V.burro + Ciocco_V.fibra return this value: 84.80000000000001 and my IF fail.... why?

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33
Andrea Bandiera
  • 109
  • 1
  • 3
  • 14

3 Answers3

1

This is because of floating point precision. It is better practice to compare the two like this:

if (((Ciocco_V.burro + Ciocco_V.fibra) - Ciocco_V.tot) > 0.00000001 ){

    //fail condition
}else{
   // correct
}
rhodysurf
  • 357
  • 1
  • 4
  • 12
  • this is too much approsimative in this contidion ((Ciocco_V.burro + Ciocco_V.fibra) - Ciocco_V.tot) > 0.00000001) the return value is: 1.4210854715202004E-14, I have modify the if condition like this: if(( Math.abs((Ciocco_V.burro + Ciocco_V.fibra) - Ciocco_V.tot) > 0.00000001) and this work well. – Andrea Bandiera Aug 29 '14 at 00:01
  • Yeah my answer wasnt tested. Glad it helped – rhodysurf Aug 29 '14 at 00:03
0

If you did a little research you could come by this: this

This questions is asked many times before!

Community
  • 1
  • 1
WHDeveloper
  • 333
  • 2
  • 14
0

you can use Double.compare(d1, d2) to compare the two values:

 int retval = Double.compare(Ciocco_V.burro + Ciocco_V.fibra, Ciocco_V.tot);
 if (retval != 0) {

 }

it returns

the value 0 if d1 is numerically equal to d2; a value less than 0 if d1 is numerically less than d2; and a value greater than 0 if d1 is numerically greater than d2.

Blackbelt
  • 156,034
  • 29
  • 297
  • 305