Search code examples
javabigdecimal

Truncate the fractional part of a BigDecimal when its scale is zero in Java


I need to remove the fractional part of a BigDecimal value when its scale has a value of zero. For example,

BigDecimal value = new BigDecimal("12.00").setScale(2, RoundingMode.HALF_UP);

It would assign 12.00. I want it to assign only 12 to value in such cases.


BigDecimal value = new BigDecimal("12.000000").setScale(2, RoundingMode.HALF_UP);

should assign 12,


BigDecimal value = new BigDecimal("12.0001").setScale(2, RoundingMode.HALF_UP);

should assign 12.


BigDecimal value = new BigDecimal("12.0051").setScale(2, RoundingMode.HALF_UP);

should assign12.01


BigDecimal value = new BigDecimal("00.000").setScale(2, RoundingMode.HALF_UP);

should assign 0.


BigDecimal value = new BigDecimal("12.3456").setScale(2, RoundingMode.HALF_UP);

should assign 12.35 and alike. Is this possible? What is the best way to do?


Solution

  • For the crosslink from there: https://codereview.stackexchange.com/questions/24299/is-this-the-way-of-truncating-the-fractional-part-of-a-bigdecimal-when-its-scale

    Is this possible? What is the best way to do?

    Probably stripTrailingZeros().

    To check your tests:

    public static void main(final String[] args) {
        check(truncate("12.000000"), "12");
        check(truncate("12.0001"), "12");
        check(truncate("12.0051"), "12.01");
        check(truncate("12.99"), "12.99");
        check(truncate("12.999"), "13");
        check(truncate("12.3456"), "12.35");
        System.out.println("if we see this message without exceptions, everything is ok");
    }
    
    private static BigDecimal truncate(final String text) {
        BigDecimal bigDecimal = new BigDecimal(text);
        if (bigDecimal.scale() > 2)
            bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
        return bigDecimal.stripTrailingZeros();
    }
    
    private static void check(final BigDecimal bigDecimal, final String string) {
        if (!bigDecimal.toString().equals(string))
            throw new IllegalStateException("not equal: " + bigDecimal + " and " + string);
    
    }
    

    output:

    if we see this message without exceptions, everything is ok