Coding Exercise 5: Decimal Comparator

2021. 2. 23. 22:33Java programming

Write a method areEqualByThreeDecimalPlaces with two parameters of type double.

 

The method should return boolean and it needs to return true if two double numbers are the same up to three decimal places. Otherwise, return false.

 

public class DecimalComparator {
    public static boolean areEqualByThreeDecimalPlaces (double num1, double num2) {
        if (Math.round(num1 * 1000) < 0 || Math.round(num2 * 1000) < 0) {
            if ((Math.abs(Math.round(num1 * 1000))) == (Math.abs(Math.round(num2 * 1000)))) {
                return true;
            } else {
                return false;
            }
        }
        if (Math.round(num1 * 1000) == Math.round(num2 * 1000)) {
            return true;
        } else {
            return false;
        }
    }
}

In order to compare between two variables by three deciaml places, multiplying by 1000 to the each variable was used while the numbers rounded by using the Math.round().