SMA_JAVA
SMA_JAVA

Reputation: 511

Less than operator evaluating for equal values also

experiencing some strange behavior while evaluating a condition which checks if a Float is less than a particular value.

    String s = "3700.7777";

    System.out.println(Float.parseFloat(s));

    if(Float.parseFloat(s) < 3700.7777){

        System.out.println("Hi");

    }

even though the value of 's' is same as that the value in condition, still the code prints "Hi". Since I am using a less than operator, my understanding was that for any value equal to or more than 3700.7777 the condition will fail and it will not print "Hi".

Upvotes: 0

Views: 110

Answers (3)

SMA_JAVA
SMA_JAVA

Reputation: 511

Guess I will use Double instead of Float. This solves my problem.

    String s = "3700.7777";

    System.out.println(Double.parseDouble(s));

    if(Double.parseDouble(s) < 3700.7777){

        System.out.println("Hi");

    }

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Please compare with appending f literal, treating that as a float value. Now it is treating that number as double

if (Float.parseFloat(s) < 3700.7777f) {

            System.out.println("Hi");

}

Upvotes: 1

Maroun
Maroun

Reputation: 95948

Change your condition to:

if(Float.parseFloat(s) < 3700.7777f) {
                                  ↑

See Primitive Data Types - float for further information.

Also you might want to know What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Upvotes: 2

Related Questions