Ankit
Ankit

Reputation: 275

Format method of String

When I am writing this code

float f=56.7876f;
System.out.print(String.format("%32.12f",f)); 

the output is: 56.787601470947

but, when I am writing this code

System.out.print(String.format("%32.12f",56.7876));

the output is: 56.787600000000

Why in both the cases different outputs are being printed despite of the fact that the functionality of both the code is same?

Upvotes: 1

Views: 277

Answers (2)

Devendra Lattu
Devendra Lattu

Reputation: 2802

Referring to why f is placed after float values? now consider this,

    float f = 56.7876f;
    System.out.print(String.format("%32.12f", f));        //                 56.787601470947
    System.out.print(String.format("%32.12f", 56.7876));  //                 56.787600000000
    System.out.print(String.format("%32.12f", 56.7876f)); //                 56.787601470947

For floating point literals the default type is double. When you say, f = 56.7876, the compiler will give warning Type mismatch: cannot convert from double to float. You would need to explicitly type cast it to float (considering the loss of precision from double to float).
In this example the output printed from 56.7876 is of type double 56.787600000000 while the rest are of type float.

To give you a better example, conider the following scenario.

    float f = 56.7874f;
    System.out.print(String.format("%32.12f", f));        //                 56.787399291992
    System.out.print(String.format("%32.12f", 56.7874));  //                 56.787400000000
    System.out.print(String.format("%32.12f", 56.7874f)); //                 56.787399291992

This clearly indicates a loss of precision from 56.7874 to 56.7873

Upvotes: 1

Anshul Sharma
Anshul Sharma

Reputation: 3522

System.out.print(String.format("%32.12f",56.7876)); it is returns 12 char fractional part filling with 0 and it consider 56.7876 as double.

you can refer following link:- https://dzone.com/articles/java-string-format-examples

Upvotes: 0

Related Questions