0

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.

  • 3
    You're returning a `double` - that doesn't have any notion of trailing zeroes. If you want to return a *specifically formatted value* then return `String` instead. (Or potentially `BigDecimal`.) – Jon Skeet May 20 '22 at 15:13
  • If you want a number represented in a specific way you should always convert them to said String representation yourself. You need to distinguish between a value of a double and its String representation. – OH GOD SPIDERS May 20 '22 at 15:14

1 Answers1

1

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

Ridiculon
  • 323
  • 4
  • 12