Alex Rivera | Logout

Check if BigDecimal is an integer in Java

Asked 2009-07-03T11:28:16.100
72

What is 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 possible.

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.

Edit
Report

1 Answer

7

You can use this (just summarizing from other answers):

private boolean isIntegerValue(BigDecimal bd) {
  return bd.stripTrailingZeros().scale() <= 0;
}
answered 2010-06-06T18:30:15.417

Your Answer