Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing float and double primitives in Java

I came across a strange corner of Java.(It seems strange to me)

double dd = 3.5;          
float ff = 3.5f;
System.out.println(dd==ff);   

o/p: true

double dd = 3.2;
float ff = 3.2f;
System.out.println(dd==ff);

o/p: false

I observed that if we compare any two values (a float and a double as I mentioned in the example) with .5 OR .0 like 3.5, 234.5, 645.0 then output is true i.e. two values are equal otherwise output is false though they are equals.

Even I tried to make method strictfp but no luck. Am I missing out on something.

like image 258
Ajinkya Avatar asked Sep 12 '11 18:09

Ajinkya


People also ask

Can you compare float and double in Java?

Though both float and double datatype are used to represent floating-point numbers in Java, a double data type is more precise than float. A double variable can provide precision up to 15 to 16 decimal points as compared to float precision of 6 to 7 decimal digits.

Can you compare float and double?

float has 7 decimal digits of precision. double is a 64-bit IEEE 754 double precision Floating Point Number – 1 bit for the sign, 11 bits for the exponent, and 52* bits for the value. double has 15 decimal digits of precision.

What is the difference between float and double data types?

A float has 7 decimal digits of precision and occupies 32 bits . A double is a 64-bit IEEE 754 double-precision floating-point number. 1 bit for the sign, 11 bits for the exponent, and 52 bits for the value. A double has 15 decimal digits of precision and occupies a total of 64 bits .

How does primitive double compare in Java?

Java double type comparison can be done through the following methods: static int compare(double d1, double d2) compares the two specified double values. int compareTo(Double anotherDouble) compares two Double objects numerically. boolean equals(Object obj) compares this object against the specified object.


1 Answers

The difference is that 3.5 can be represented exactly in both float and double - whereas 3.2 can't be represented exactly in either type... and the two closest approximations are different.

Imagine we had two fixed-precision decimal types, one of which stored 4 significant digits and one of which stored 8 significant digits, and we asked each of them to store the number closest to "a third" (however we might do that). Then one would have the value 0.3333 and one would have the value 0.33333333.

An equality comparison between float and double first converts the float to a double and then compares the two - which would be equivalent to converting 0.3333 in our "small decimal" type to 0.33330000. It would then compare 0.33330000 and 0.33333333 for equality, and give a result of false.

like image 98
Jon Skeet Avatar answered Sep 20 '22 07:09

Jon Skeet