I have a Java application which parses a number from somewhere, and checks that it is a valid int (between Integer.MIN_VALUE and Integer.MAX_VALUE) or a valid double (between Double.MIN_VALUE and Double.MAX_VALUE).
I'm using this code:
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 v开发者_JS百科oid 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")));
}
}
Which works fine for int values, but for some reason, fails for any zero or negative double value. So running the above produces the output:
true
true
true
true
false
false
What am I doing wrong here?
Also, I've seen examples where DOUBLE_MIN is set to be -Double.MAX_VALUE. This works but is it correct?
Thanks.
Double.MIN_VALUE
represents the minimum positive value. (That is, a positive value close to zero.)
From the documentation:
A constant holding the smallest positive nonzero value of type double, 2-1074.
This is the reason why
System.out.println(inRange(new BigDecimal("0.0")));
System.out.println(inRange(new BigDecimal("-987.0")));
outputs false. None of the provided values are (strictly) greater than 0.
The solution
Since the range of double
s are symmetrical around origo (as opposed to integers, which stretches one step further on the negative side) you can get the minimum (negative) value by writing -Double.MAX_VALUE
. That is
BigDecimal DOUBLE_MIN = BigDecimal.valueOf(-Double.MAX_VALUE);
If you see the javadoc for Double.MIN_VALUE it says
A constant holding the smallest **positive nonzero** value of type
<code>double</code>
精彩评论