0

I've tried executing the below program and the output looks unusual.

public class FloatingPointIssue {

public static strictfp void main(String[] args) {

    float floatValue  = 277677.86f;
    double doubleValue  = 277677.86;

    System.out.println(floatValue);
    System.out.println(doubleValue);

}

Output :

277677.88 277677.86

There is absolutely no issue using double but when I tried the same with float, the output is not as expected. Can someone try to explain me what's happening internally(while using float) that actually caused this issue.

Many thanks :)

  • 1
    `float` can't hold the value `277677.86`; see the linked question's answers for details. The nearest it can come is a value which either is `277677.88` or is nearer to that than to any other value `float` can hold. (When being output, `float` and `double` only output as many digits as needed to differentiate them from the next representable value, even if the value they're holding would go to more decimal places. [In fact, I think the value is just under `277677.88`, in the region of `277677.875`, but I'm not good at IEEE-754 bit fiddling.]) – T.J. Crowder Apr 12 '17 at 10:45
  • Thank you @T.J.Crowder for the response. It would be a great help if you can elaborate your answer or provide any documentation related to this.Also, when its able to hold 277677.88, why not 277677.86 – Shiva kumar Apr 12 '17 at 10:55
  • The linked question's answers and research into IEEE-754 single-precision binary floating point should get you any information you need. Also see [`Float.toString(float)`](http://docs.oracle.com/javase/8/docs/api/java/lang/Float.html#toString-float-): *"How many digits must be printed for the fractional part of* m *or* a *? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type `float`."* – T.J. Crowder Apr 12 '17 at 10:58

0 Answers0