0

I'm currently writing a Junit test where I use assertEquals() to compare the value of two ArrayList<Double>.

@Test
public void test(){

        QuadraticFormula one = new QuadraticFormula(3, 4, -4);
        List<Double> results = new ArrayList<>();
        results.add(0.66666);
        results.add(-2.0);

        assertEquals(results, one.getRoots());
    }

However, Junit prints out the following failure message:

expected:<[0.66666, -2.0]> but was:<[0.6666666666666666, -2.0]>
junit.framework.AssertionFailedError

Is there anyway I can specify how many decimal places I want the test to compare? I know how to test equality of two double values to certain accuracy, but is there anyway that this can be achieved when comparing two ArrayList of doubles?

halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137

2 Answers2

1

I guess you can use BigDecimal instead of Double.

check this SO for more details

Community
  • 1
  • 1
Beniton Fernando
  • 1,533
  • 1
  • 14
  • 21
1

You can use NumberFormat or BigDecimal

Below will round-of

    double d = 0.66666666;
    NumberFormat format = new DecimalFormat("#.##");
    System.out.println(format.format(d)); // 0.67
    BigDecimal bigDecimal = new BigDecimal(d);
    bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(bigDecimal); // 0.67

If you don't want to round-of

    double d = 0.66666666;
    DecimalFormat format = new DecimalFormat("#.##");
    format.setRoundingMode(RoundingMode.DOWN);
    System.out.println(format.format(d)); // 0.66
    BigDecimal bigDecimal = new BigDecimal(d);
    bigDecimal = bigDecimal.setScale(2, RoundingMode.DOWN);
    System.out.println(bigDecimal); //0.66
Saravana
  • 12,647
  • 2
  • 39
  • 57