我编写测试并希望将 BigDecimal 结果与预期值进行比较。
我要使用方法 Assert.assertEquals(BigDecimal, BigDecimal)
因为如果放下它会显示精确的比较值,而在 Eclipse 中我可以显示比较窗口。
所以在代码中我有返回 BigDecimal 四舍五入到小数点后两位的方法。 在测试用例中,我现在返回没有非零十进制数字的数字。所以我想创建比例为 0 的 BigDecimal 并将返回的 BigDecimal 修剪为相同的比例。
为了更复杂,我现在有方法 getDecimal(Object [,Optionaly int scale])
从任何具有正确 toString()
的对象创建 BigDecimal默认比例为 99 的值。我在主要的“重”代码中使用它,所以这个方法必须非常快(不需要创建另一个对象,不要使用正则表达式等)。
如此简单的问题是:如何修改 BigDecimal 实例以通过最小负载修剪结尾的小数零。
想要这样的srip
0.010 -> 0.01
5.000 -> 5
100 -> 100 not 1E+2
响应:
someTrim(new BigDecimal("100.00")).equals(new BigDecimal(100))
做数学之类的事情
100.00 / (2, 99, DOWN) * 50.00 -> 2500
我的代码看起来像
public static BigDecimal getDecimal( Object value ) {
// null here probably work beter, but dont want number longer then 99 decimal digits
return getDecimal( value, 99 );
}
public static BigDecimal getDecimal( Object value, Integer scale ) {
if ( value == null )
return null;
BigDecimal result = ( value instanceof BigDecimal ) ? ( BigDecimal ) value : new BigDecimal( value.toString() );
if ( scale == null )
return result;
return result.setScale( scale, DOWN );
}
// Main heavy method could call this 100 000 times per tenant (cca 1500 tenants), of course not expect all in same time, but can severals
public static myModify(E entity){
return myModify( entity.getValue(), entity.getDivisor(), entity.getMultiplicator() );
}
public static myModify( BigDecimal value, Integer divisor, BigDecimal multiplicator){
return value.divide( getDecimal(divisor), 99, RoundingMode.DOWN ).multiply( multiplicator );
}
@Test
public void myModifyTest(){
// Constructor have param: value, divisor, multiplicator
E entity = new E(new BigDecimal("100.00"), 2, new BigDecimal("50.00"));
// Should pass
Assert.assertEquals(getDecimal(100), entity);
// Should drop: java.lang.AssertionError: expected:<50> but was:<100>
Assert.assertEquals(getDecimal(50), entity);
// Not want: java.lang.AssertionError: expected:<5E+1> but was:<1E+2>
}
也许存在另一种 junit 比较方法会抛出相同的错误,但我不知道
感谢您的帮助。帕维尔
最佳答案
official junit solution这个要求是使用 hamcrest。
与 java-hamcrest 2.0.0.0我们可以使用这种语法:
BigDecimal a = new BigDecimal("100")
BigDecimal b = new BigDecimal("100.00")
assertThat(a, Matchers.comparesEqualTo(b));
关于java - 从 BigDecimal 中删除小数结尾的零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42829933/