[英]In Junit testing, how to comparing two ArrayList<Double> using assertEquals(), and is there an better alternative?
I'm currently writing a Junit test where I use assertEquals()
to compare the value of two ArrayList<Double>
. 我目前正在编写Junit测试,其中使用assertEquals()
比较两个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: 但是,Junit会打印出以下失败消息:
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? 我知道如何测试两个double值的相等性到一定的精度,但是无论如何,在比较两个ArrayList的double时是否可以实现?
You can use NumberFormat
or BigDecimal
您可以使用NumberFormat
或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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.