Is this the way of truncating 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("12.99").setScale(2, RoundingMode.HALF_UP);


should assign 12.99.



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


should assign13



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


should assign 12.35 and alike.



I have this question on StackOverflow.

For this to be so, I'm doing the following.

String text="123.008";
BigDecimal bigDecimal=new BigDecimal(text);

if(bigDecimal.scale()&gt;2)
{
    bigDecimal=new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
}

if(bigDecimal.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO)==0)
{
    bigDecimal=new BigDecimal(text).setScale(0, BigDecimal.ROUND_HALF_UP);
}

System.out.println("bigDecimal = "+bigDecimal);


It's just as an example. Is there a better way to do this?
Is there a better way to do this?


Yes, 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() &gt; 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