简体   繁体   中英

Return value isn't returning double with two decimal places

This question goes towards both my class method and my test cases. I have tried searching it up and implemented some of the methods I found online, but in my test case, it shows as Expected: 10.0 Actual: 11.0 when I want it to show Expected: 10.00 Actual: 11.00 with trailing zeros. It works if it's a number that's not zero, so Expected: 12.33 Actual: 12.33 is good.

My issue is mainly with trailing zeros.

code in class method:

public Double average(int[] scores) {
        double average = Arrays.stream(scores).average().orElse(0.00);
        String format = String.format("%.2f", average);

        for (int num : scores) {
            if (num < 0) throw new ArithmeticException("scores must be positive");
        }

        return Double.parseDouble(format);
    }

test case: I originally had a double value (10.00) but changed it to a BigDecimal and then converted it to a double to see if it would work, but ig not.

public void testSingleAverage() {
        int[] nums = {11};

        BigDecimal expected = new BigDecimal(10.00).setScale(2);
        Double result = exercise.average(nums);
        Double value = expected.doubleValue();


        assertEquals(value, result);
    }

Thank you in advance for the help <3

Edit: I'm not able to return a String or BigDecimal(even tho its much simpler). Its required to be a double value.

There is no way to force a double to have trailing zeros. If you take a look at theDouble class you will see that there is no concept of precision or scale included (like there is for the BigDecimal class).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM