0

From the code below, after subtracting, in this case, for the variables numDiff1 and numDiff2, to chop off the whole number, the variable numDiff2 is reduced to -0.174999999 which doesn't make sense as it is supposed to be -0.175. There seems to be a Bug in Java. Please let me know. Thank you. Is there any other alternative for this?

public static boolean areEqualByThreeDecimalPlaces(double numOne, double numTwo){

//For the first parameter
int num1 = (int) numOne;
double numDiff1 = numOne - num1; // numDiff1 = -0.1756000000000002
numDiff1*=1000;
int numFin1 = (int)numDiff1;

//Second parameter
int num2 = (int) numTwo;
double numDiff2 = numTwo - num2; numDiff2 = -0.17499999999999982
numDiff2*=1000;
int numFin2 = (int) numDiff2;


if(numFin1 == numFin2){
    return true;
}else{
    return false; //False
}

}

  • See https://en.wikipedia.org/wiki/Loss_of_significance. – enzo Sep 06 '20 at 14:31
  • 1
    "There seems to be a Bug in Java" - it's a good idea to always *start* with the expectation that the problem is in your understanding, rather than in software used by hundreds of thousands of developers. In this case, I believe the problem is your understanding of how floating point numbers are represented. – Jon Skeet Sep 06 '20 at 14:33
  • (Just occasionally the problem will really be in the widely-used software, but if you start with the *expectation* that that's the case, you'll miss the many, many opportunities to correct your own understanding.) – Jon Skeet Sep 06 '20 at 14:34

0 Answers0