The following simple code in Java contains hardly 3 statements that returns unexpectedly false though it looks like that 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 obviously display true on the console but it doesn't. It displays false instead. Why?
This happens because floating point arithmetic != real number arithmetic.
When f
is assigned 2000000000
, it gets converted to 2.0E9
. Then when you add 50 to 2.0E9
, its value doesn't change. So actually, (f == temp + 50)
is true
.
If you need to work with large numbers but require precision, you'll have to use something like BigDecimal
:
long temp = 2000000000;
BigDecimal d = new BigDecimal(temp);
System.out.println(d.compareTo(new BigDecimal(temp+50)) < 0);
Will print true
as one would expected.
(although in your case I don't know why you'd need to use a datatype other than long
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With