Simple Java code that unexpectedly returns false when it intends to return true

The following simple Java code contains just 3 statements that unexpectedly return false , although it looks like it should return true .

package temp; final public class Main { public static void main(String[] args) { long temp = 2000000000; float f=temp; System.out.println(f<temp+50); } } 

The above code should explicitly display true on the console, but it is not. It displays false . Why?

+4
source share
1 answer

This is because floating point arithmetic! = Real number arithmetic .

When f is assigned 2000000000 , it is converted to 2.0E9 . Then, when you add 50 to 2.0E9 , its value does not change. So (f == temp + 50) true .

If you need to work with large numbers, but you need precision, you will need to use something like BigDecimal :

 long temp = 2000000000; BigDecimal d = new BigDecimal(temp); System.out.println(d.compareTo(new BigDecimal(temp+50)) < 0); 

true will be printed as expected.

(although in your case I don't know why you need to use a data type other than long ).

+14
source

Source: https://habr.com/ru/post/1381604/


All Articles