Float numbers in Java

若如初见. 提交于 2019-11-28 02:01:17

6.5 has a finite binary representation: 110.1

Any floating type with at least 4 significant bits can represent this number perfectly.

110.100000000000000000000 (float)
= 6.5

110.10000000000000000000000000000000000000000000000000 (double)
= 6.5

3.2 on the other hand has an infinite binary representation: 101.0011001100110011...

float and double don't have infinite precision and thus can only approximate this number :(

101.001100110011001100110 (float)
= 3.2000000476837158203125

101.00110011001100110011001100110011001100110011001101 (double)
= 3.20000000000000017763568394002504646778106689453125

As you can clearly see, these numbers are not the same!

Because 3.2 is not representable exactly as floating point number and 6.5 is (hint: 6.5 = 13 * 2^(-1)), as well as the fact that 3.2 is a double literal but 3.2f is a float literal.

Because 3.2f is a float value and 3.2 is a double value. Floating point numbers are always slightly inaccurate because binary representation cannot implement them accurately, so comparing them for exact equality is a bad idea. Particularly comparing floats with doubles. Expressions such as 3.2f == 3.2f are usually okay, but even those can fail in some languages, e.g. if they represent numbers in registers more accurately than in memory.

This can help understand

"3.2f" is a of type float. "3.2" is of type double.

Also, I think anything with a decimal defaults into a double, so when you do a comparison, you have to add 'f' as well like if(f2==6.4f).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!