0

How do we check the negative number is out of range for float variable in Java?

If I use Float.parseFloat("1.4E-46"), it returns 0.0 instead of negative infinite. In the case of positive bigger number, it returns infinite.

The below code works for positive number, am looking something similar for negative number.

    Float f = Float.valueOf(Float.parseFloat(input));

    if (f.floatValue() > Float.MAX_VALUE) {
        return false;
    }
skumar
  • 985
  • 4
  • 14
  • 37
  • The reverse is the theoretical `MIN_VALUE`, that is negative of the `MAX_VALUE` ` – kolossus Mar 31 '15 at 18:38
  • possible duplicate of [min value of float in java is positive why?](http://stackoverflow.com/questions/9746850/min-value-of-float-in-java-is-positive-why) – kolossus Mar 31 '15 at 18:39
  • 1
    `1.4E-46` is positive, not negative. It's a really small number. – k_g Mar 31 '15 at 18:40
  • Ok. how it should be checked for very small number and it can't be hold under float variable. I believe the min and max value for float are 1.4E-45 & 3.4028235E38 – skumar Mar 31 '15 at 18:48

2 Answers2

6

If I use Float.parseFloat("1.4E-46"), it returns 0.0 instead of negative infinite. In the case of positive bigger number, it returns infinite.

The number 1.4E-46 is not a negative number. It is a very small positive number.

The opposite of 1.4E+46 is -1.4E+46. So if you do Float.valueOf("-1.4E+46") you will get -Infinity.

Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
  • thanks for this. Can you please tell me how to check the value is very small positive value & it's not in float limit? does Float Wrapper class have any method to check for this? – skumar Mar 31 '15 at 18:51
  • If you try to do `Float.valueOf()` on a positive number and the result is `0.0`, it means that the number is too small to be represented by a `float` other than `0.0`. – Anderson Vieira Mar 31 '15 at 18:57
4

That is not a negative number; it is an extremely small positive number. This is "computerized" scientific notation. 1.4E-46 is equivalent to 1.4 x 10-46.

The Float.parseFloat method parses the number the same as Float.valueOf(String), whose javadocs state:

if the exact value of s is small enough in magnitude (less than or equal to MIN_VALUE/2), rounding to float will result in a zero.

Java's parsing method determined that the value is less than Float.MIN_VALUE / 2, so it returned a 0.0.

rgettman
  • 176,041
  • 30
  • 275
  • 357