Can anyone recommend an efficient way of determining whether a BigDecimal
is an integer value in the mathematical sense?
At present I have
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;
}