从 BigDecimal 中删除小数结尾零

Per*_*los 5 java junit

我编写测试并希望将BigDecimal结果与预期值进行比较。我想要使​​用方法Assert.assertEquals(BigDecimal, BigDecimal),因为如果删除它会显示精确的比较值,并且在 Eclipse 中我可以显示比较窗口。

所以在代码中我有一个方法返回BigDecimal四舍五入到小数点后两位。在测试用例中,我现在返回不带非零十进制数字的数字。所以我想创建比例为 0 的BigDecimal并将返回的BigDecimal修剪为相同的比例。

为了更复杂,我现在有方法从任何具有正确值的对象getDecimal(Object [,Optionaly int scale])创建BigDecimaltoString(),默认比例为 99。我在主要的“重”代码中使用它,所以这个方法必须非常快(不需要创建另一个对象,不要使用正则表达式等。 )。

所以简单的问题是:如何修改BigDecimal实例以通过最小负载修剪结尾的小数零。

想要这样的片子

0.010 -> 0.01
5.000 -> 5
100 -> 100   not 1E+2
Run Code Online (Sandbox Code Playgroud)

回复:

someTrim(new BigDecimal("100.00")).equals(new BigDecimal(100))
Run Code Online (Sandbox Code Playgroud)

做数学之类的事情

100.00 / (2, 99, DOWN) * 50.00 -> 2500
Run Code Online (Sandbox Code Playgroud)

我的代码看起来像

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>
}
Run Code Online (Sandbox Code Playgroud)

也许存在另一种 junit 比较方法,它会产生相同的错误,但我不知道

感谢帮助。帕维尔

Per*_*los 1

我可能找到了解决方案。创建另一个 BigDecimal 实例是不好的,但不知道另一种侵入性较小的方法。如果没有必要,我会做一些优化来不创建实例。

/** 
 * For text comparsion or log propouse
 * @return human readable text without decimal zeros 
 */
public static String getPlainText( BigDecimal value ) {
    if ( value == null )
        return null;

    // Strip only values with decimal digits
    BigDecimal striped = ( value.scale() > 0 ) ? value.stripTrailingZeros() : value;
    return striped.toPlainString();
}

/** 
 * For comparison by equals method like test assertEquals
 * @return new instance without decimal zeros 
 */
public static BigDecimal stripDecimalZeros( BigDecimal value ) {
    if ( value == null )
        return null;

    // Strip only values with decimal digits
    BigDecimal striped = ( value.scale() > 0 ) ? value.stripTrailingZeros() : value;
    // Unscale only values with ten exponent
    return ( striped.scale() < 0 ) ? striped.setScale( 0 ) : striped;
}
Run Code Online (Sandbox Code Playgroud)

感谢@frhack。可以为测试编写类似于 OrderingComparsion 的 Macther 类。简单的等于

public static class BigDecimalEqualComparator extends TypeSafeMatcher<BigDecimal> {

    private final BigDecimal expected;

    private static final String[] comparisonDescriptions = { "less than", "equal to", "greater than" };

    public BigDecimalEqualComparator( BigDecimal expected ) {
        this.expected = expected;
    }

    @Override
    public boolean matchesSafely( BigDecimal actual ) {
        return actual.compareTo( expected ) == 0;
    }

    // You must change this
    @Override
    public void describeMismatchSafely( BigDecimal actual, Description mismatchDescription ) {
        mismatchDescription.appendValue( actual.stripTrailingZeros().toPlainString() ).appendText( " was " )
            .appendText( asText( actual.compareTo( expected ) ) ).appendText( " " )
            .appendValue( expected.stripTrailingZeros().toPlainString() );
    }

    @Override
    public void describeTo( Description description ) {
        description.appendText( "a value equal to " ).appendValue( expected.stripTrailingZeros().toPlainString() );
    }

    private static String asText( int comparison ) {
        return comparisonDescriptions[signum( comparison ) + 1];
    }
}
Run Code Online (Sandbox Code Playgroud)