Check if BigDecimal is integer value
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;
}
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.
Divide the number by 1 and check for a remainder. Any whole number should always have a remainder of 0 when divided by 1.
public boolean isWholeNumber(BigDecimal number) {
return number.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0;
}