代码之家  ›  专栏  ›  技术社区  ›  Adamski

检查bigdecimal是否为整数值

  •  41
  • Adamski  · 技术社区  · 16 年前

    有人能推荐一个 有效率的 确定是否 BigDecimal 是数学意义上的整数值吗?

    目前我有以下代码:

    private boolean isIntegerValue(BigDecimal bd) {
        boolean ret;
    
        try {
            bd.toBigIntegerExact();
            ret = true;
        } catch (ArithmeticException ex) {
            ret = false;
        }
    
        return ret;
    }
    

    …但如果需要,希望避免对象创建开销。以前我用过 bd.longValueExact() 如果 双小数 在内部使用了它的紧凑表示,但如果值太大而不能容纳一个长值,显然会失败。

    感谢您的帮助。

    7 回复  |  直到 16 年前
        1
  •  13
  •   Joachim Sauer    16 年前

    取决于您的 BigDecimal 如果先检查比例<=0,则可能更快。如果是,那么它绝对是一个数学意义上的整数值。如果是>0,则 能够 仍然是整数值,需要更昂贵的测试。

        2
  •  60
  •   Jerry Jiang tobi    6 年前

    编辑:对于Java 8,StutTraceLIZONEOSE()现在占零

    BigDecimal stripTrailingZeros doesn't work for zero

    所以

    private boolean isIntegerValue(BigDecimal bd) {
      return bd.stripTrailingZeros().scale() <= 0;
    }
    

    现在很好。


    如果您使用 scale() stripTrailingZeros() 一些答案中提到的解决方案应该注意零。零总是一个整数,不管它有多大的刻度,以及 striptrailingzeros()。 不更改零BigDecimal的小数位数。

    所以你可以这样做:

    private boolean isIntegerValue(BigDecimal bd) {
      return bd.signum() == 0 || bd.scale() <= 0 || bd.stripTrailingZeros().scale() <= 0;
    }
    
        3
  •  5
  •   ooxi    7 年前

    将数字除以1,然后检查余数。任何整数除以1时都应该有0的余数。

    public boolean isWholeNumber(BigDecimal number) {
        return number.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0;
    }
    
        4
  •  4
  •   emisch    15 年前

    您可以使用此选项(仅从其他答案汇总):

    private boolean isIntegerValue(BigDecimal bd) {
      return bd.stripTrailingZeros().scale() <= 0;
    }
    
        5
  •  2
  •   Kosi2801    16 年前

    一个可能的方法是检查 scale() 为零或负。在这种情况下,bigdecimal应该在小数点后没有数字,如果我正确理解您的问题,那么这个数字应该是一个数学整数。

    更新 :如果为正数,则它仍然可以是一个整数,但在这种情况下,不能为进一步的深入检查保留额外的对象创建。 例如,在 stripTrailingZeros() 方法JavaDoc(感谢Joachim在回答中给出的提示)。

        6
  •  1
  •   Scott Armstrong    7 年前

    这与某人检查double是否为整数的方式相同,执行%1==0。这就是它查找bigdecimal值的方式。

    public static boolean isIntegerValue(BigDecimal bd){
      return bd.remainder(new BigDecimal("1")).compareTo(BigDecimal.ZERO) == 0;
    }
    
        7
  •  0
  •   Ian    10 年前

    这是我想到的最干净的。

    public static boolean isWhole(BigDecimal bigDecimal) {
        return bigDecimal.setScale(0, RoundingMode.HALF_UP).compareTo(bigDecimal) == 0;
    }