Reputation: 10058
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?
Upvotes: 0
Views: 509
Reputation: 12817
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
Upvotes: 1
Reputation: 1533
I guess you can use BigDecimal instead of Double.
check this SO for more details
Upvotes: 1