Check if BigDecimal is integer value

Adamski picture Adamski · Jul 3, 2009 · Viewed 42.7k times · Source

Can anyone recommend an efficient way of determining whether a BigDecimal is an integer value in the mathematical sense?

At present I have the following code:

private boolean isIntegerValue(BigDecimal bd) {
    boolean ret;

    try {
        bd.toBigIntegerExact();
        ret = true;
    } catch (ArithmeticException ex) {
        ret = false;
    }

    return ret;
}

... but would like to avoid the object creation overhead if necessary. Previously I was using bd.longValueExact() which would avoid creating an object if the BigDecimal was using its compact representation internally, but obviously would fail if the value was too big to fit into a long.

Any help appreciated.

Answer

tobi picture tobi · Oct 5, 2012

EDIT: As of Java 8, stripTrailingZeroes() now accounts for zero

BigDecimal stripTrailingZeros doesn't work for zero

So

private boolean isIntegerValue(BigDecimal bd) {
  return bd.stripTrailingZeros().scale() <= 0;
}

Is perfectly fine now.


If you use the scale() and stripTrailingZeros() solution mentioned in some of the answers you should pay attention to zero. Zero always is an integer no matter what scale it has, and stripTrailingZeros() does not alter the scale of a zero BigDecimal.

So you could do something like this:

private boolean isIntegerValue(BigDecimal bd) {
  return bd.signum() == 0 || bd.scale() <= 0 || bd.stripTrailingZeros().scale() <= 0;
}