Search code examples
javafloating-pointieee-754

Why is my float being truncated?


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?


Solution

  • 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