BigDecimal - check value is within double range

ε祈祈猫儿з 提交于 2019-12-22 12:58:16

问题


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

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.


回答1:


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 doubles 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);



回答2:


If you see the javadoc for Double.MIN_VALUE it says

 A constant holding the smallest **positive nonzero** value of type
 <code>double</code>


来源:https://stackoverflow.com/questions/5411637/bigdecimal-check-value-is-within-double-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!