1

Why am I not getting expected output when using the String.format() function? The answer should be 123456789.123456789 right?

main()
{
    float a = 123456789.123456789f; 
    System.out.println(String.format("%f", a));   // Actual Output: 123456792.000000 
    System.out.println(String.format("%.4f", a)); // Actual Output: 123456792.0000 
    System.out.println(String.format("%.4f", a)); // Actual Output: 123456792.0000 
}
BSMP
  • 4,596
  • 8
  • 33
  • 44

1 Answers1

2

Float is 32bit. You just overflowed it and it was added to the integer part of number

  • Thanks! Can you tell me how it works? I mean how the overflow part was added to the Integer part? – Karthik kashyap May 20 '21 at 06:23
  • Oh, it's very dirty business :D You should find out it yourself in _Oracle docs_. Sorry. With double it's more clearly. But float have mantissa, exponenta, and it's difficult to remember how it works. – LoliDeveloper May 20 '21 at 06:56