Why is my float being truncated?

我们两清 提交于 2019-12-24 02:23:36

问题


Entering a value such as 27.8675309 into the "Decimal representation" field of the IEEE 754 Converter changes the value I entered to 27.86753. Likewise, Java drops the last two digits when a parse a string with the same value.

Float.parseFloat("27.8675309") // Results in a float value of 27.86753

I am not sure what the "Decimal representation" of the IEEE converter actually is (is it a float?) but I would expect it to give me the biggest number possible that:

  1. Is a float value
  2. Does not exceed the original value I entered

I would expect Java to behave in a similar fashion, that is, I would expect the line of code above to return a float value equal to 27.8675308 or an even larger float value that is closer to my original input instead of just dropping decimal places. What am I missing here?


回答1:


This is as expected.

If you look at the binary representation of 27.8675309 (27.867530822753906 as a double):

01000001110111101111000010110100

the next highest value is:

01000001110111101111000010110101

which yields 27.867533 (27.86753273010254 as a double), and the next lowest value is:

01000001110111101111000010110011

which yields 27.867529 (27.867528915405273 as a double)

There simply aren't enough bits in the mantissa of a Float to represent any value in between, so your value is rounded down in decimal to 27.867530




回答2:


As Alnitak mentioned, you've run out of bits. You could use Double for higher precision, though. Double implements 64-bit IEEE 754 floating point whereas Float implements 32-bit IEEE 754 floating point.



来源:https://stackoverflow.com/questions/9083905/why-is-my-float-being-truncated

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