AssertJ比较双精度浮点数值

4

我想使用AssertJ比较双精度数值,但是我不知道为什么我的测试失败了。

@Test
public void testInterestToQuote() {
    double result = BasicCalculator.accumulationFactorByYearsAndInterest(years, interest)
    Assertions.assertThat(result).isCloseTo(expected, Assertions.offset(0.1d))
}

异常是:

java.lang.AssertionError: 
Expecting:
   <7.256571590148141E-5>
to be close to:
   <7.25>
by less than <0.1> but difference was <7.249927434284099>.
(a difference of exactly <0.1> being considered valid)

断言为什么会失败?

2个回答

2
昨天晚了,但7.256571590148141E-5并不像我想的那样是7.25..,因为E-5将小数点向左移动了5位,所以它是0.0000725...。

11
如果有人正在寻找使用AssertJ进行带有特定精度的小数点比较,并最终到达了这里。正确的方法应该是像这样:assertThat(result).isEqualTo(expected, withPrecision(2d)) - atavio

0
在我的情况下,我正在比较Double和Float。

assertThat(resultDouble).isEqualTo(expectedFloat);

断言结果值(resultDouble)应等于期望值(expectedDouble)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接