Check if BigDecimal is integer value

前端 未结 7 2164
有刺的猬
有刺的猬 2021-02-03 17:36

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

At present I have

7条回答
  •  心在旅途
    2021-02-03 17:54

    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;
    }
    

提交回复
热议问题