Home > OS >  Compare two double values in Java
Compare two double values in Java

Time:12-05

This is a Java code that should test whether the first three digits after the decimal point are identical. And I need to write this program without a main method.

public class areEqualByThreeDecimalPlaces {
    public static boolean areEqualByThreeDecimalPlaces(double d_1, double d_2) {
        double value_1 = Math.round(1000*d_1);
        double value_2 = Math.round(1000*d_2);

        if (value_1 == value_2) {
            return true;
        } else return false;
    }
}

Input:

(-3.1756, -3.175)

Expected Output:

true

Output received:

false

By using the Math.round it is rounding the value of -3.1756 to -3.176. But I want to check if the three digits after the decimal point are similar.

How do I correct my code?

CodePudding user response:

Going off this code the two values just won't be equal. value_1 = -3176.0 value_2 = -3175.0

If you want to learn a little more about truncating doubles, take a look at this. How can I truncate a double to only two decimal places in Java?

CodePudding user response:

You could to use ceil instead of round

double value_1 = Math.ceil(d_1 * 1000);
double value_2 = Math.ceil(d_2 * 1000);

Fabio

  • Related