Note that there are some explanatory texts on larger screens.

plurals
  1. POBigDecimal - check value is within double range
    primarykey
    data
    text
    <p>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).</p> <p>I'm using this code:</p> <pre><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) &gt;= 0 &amp;&amp; DOUBLE_MIN.compareTo(value) &lt;= 0; } private static boolean inRange(BigInteger value) { return INTEGER_MAX.compareTo(value) &gt;= 0 &amp;&amp; INTEGER_MIN.compareTo(value) &lt;= 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"))); } } </code></pre> <p>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:</p> <pre><code>true true true true false false </code></pre> <p>What am I doing wrong here?</p> <p>Also, I've seen examples where DOUBLE_MIN is set to be -Double.MAX_VALUE. This works but is it correct?</p> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload