0

This Java code below is not returning true in if else statement...

public class DecimalComparator {

    public static void main(String[] args) {
        System.out.println(areEqualByThreeDecimalPlaces(25.367876,25.367873));
    }

    public static boolean areEqualByThreeDecimalPlaces(double a, double b){

        DecimalFormat threePreshizen = new DecimalFormat("###.###");
        String aNew = threePreshizen.format(a);
        String bNew = threePreshizen.format(b);

        System.out.println(aNew);
        System.out.println(bNew);

        if (aNew == bNew){
            return true;
        }else {
            return false;
        }
    }
}

I expect it to return "true".

TheWhiteRabbit
  • 1,253
  • 1
  • 5
  • 18

1 Answers1

0

Replace your if block with the following:

return aNew.equals(bNew);

This returns a boolean based on if content of the two strings matches, rather than if the value of their memory reference is identical.

If you expect either of your strings to be null, instead use

return Objects.equals(aNew, bNew);
Austin Schaefer
  • 695
  • 5
  • 19