BigDecimal - 检查值在双倍范围内

R C*_*ell 2 java double bigdecimal

我有一个Java应用程序,它从某个地方解析一个数字,并检查它是一个有效的int(在Integer.MIN_VALUE和Integer.MAX_VALUE之间)还是一个有效的double(在Double.MIN_VALUE和Double.MAX_VALUE之间).

我正在使用此代码:

import java.math.BigDecimal;
import java.math.BigInteger;

  public class Test  {

    public static final BigDecimal DOUBLE_MAX = BigDecimal.valueOf(Double.MAX_VALUE);
    public static final BigDecimal DOUBLE_MIN = BigDecimal.valueOf(Double.MIN_VALUE);

    public static final BigInteger INTEGER_MIN = BigInteger.valueOf(Integer.MIN_VALUE);
    public static final BigInteger INTEGER_MAX = BigInteger.valueOf(Integer.MAX_VALUE);

    private static boolean inRange(BigDecimal value) {
        return DOUBLE_MAX.compareTo(value) >= 0 &&
          DOUBLE_MIN.compareTo(value) <= 0;
    }

    private static boolean inRange(BigInteger value) {
        return INTEGER_MAX.compareTo(value) >= 0 &&
          INTEGER_MIN.compareTo(value) <= 0;
    }

    public static void main(String[] args)
    {
        System.out.println(inRange(new BigInteger("1234656")));
        System.out.println(inRange(new BigInteger("0")));
        System.out.println(inRange(new BigInteger("-987")));

        System.out.println(inRange(new BigDecimal("1234656.0")));
        System.out.println(inRange(new BigDecimal("0.0")));
        System.out.println(inRange(new BigDecimal("-987.0")));
    }
  }
Run Code Online (Sandbox Code Playgroud)

哪个适用于int值,但由于某种原因,任何零或负双值都会失败.所以运行上面会产生输出:

true
true
true
true
false
false
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

另外,我见过将DOUBLE_MIN设置为-Double.MAX_VALUE的示例.这有效,但它是否正确?

谢谢.

aio*_*obe 6

Double.MIN_VALUE代表最小正值.(也就是说,正值接近于零.)

从文档:

保持double类型的最小正非零值的常量,2 -1074.

这就是原因所在

System.out.println(inRange(new BigDecimal("0.0")));
System.out.println(inRange(new BigDecimal("-987.0")));
Run Code Online (Sandbox Code Playgroud)

输出错误.所提供的值都不是(严格地)大于0.


解决方案

由于doubles 的范围在origo周围是对称的(与整数相反,在负侧延伸一步),你可以通过写入获得最小(负)值-Double.MAX_VALUE.那是

BigDecimal DOUBLE_MIN = BigDecimal.valueOf(-Double.MAX_VALUE);
Run Code Online (Sandbox Code Playgroud)