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.
Depending on the source/usage of your BigDecimal
values it might be faster to check if the scale <= 0 first. If it is, then it's definitely an integer value in the mathematical sense. If it is >0, then it could still be an integer value and the more expensive test would be needed.