我有一个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")));
}
}
这对于 int 值工作得很好,但由于某种原因,对于任何零或负双精度值都失败。因此运行上面的命令会产生输出:
true
true
true
true
false
false
我在这里做错了什么?
另外,我还看到过 DOUBLE_MIN 设置为 -Double.MAX_VALUE 的示例。这可行,但是正确吗?
Thanks.
Double.MIN_VALUE
代表最小值positive价值。 (即接近于零的正值。)
From 文档 http://download.oracle.com/javase/6/docs/api/java/lang/Double.html:
A constant holding the smallest positive nonzero value of type double, 2-1074.
这就是为什么
System.out.println(inRange(new BigDecimal("0.0")));
System.out.println(inRange(new BigDecimal("-987.0")));
输出假。所提供的值都不(严格)大于 0。
解决方案
由于范围为double
s 围绕 origo 对称(与整数相反,整数在负侧进一步延伸一步),您可以通过以下方式获得最小(负)值-Double.MAX_VALUE
。那是
BigDecimal DOUBLE_MIN = BigDecimal.valueOf(-Double.MAX_VALUE);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)