Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is format specifier %.3f giving an error in Java?

So I am trying to print first 3 digits of PI using floating point format specifier in java, using the following code:

public class PrettyPrinting {
    public static void main(String[] args) {
        float a = 453.1274f;
        System.out.printf("Formatted number is %.2f \n", a);

        System.out.printf("Pi is: %.3f \n" + (float)Math.PI);
    }
}
 

And it is giving me the following Exception stack trace:

Formatted number is 453.13 
Pi is: Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%.3f'
    at java.base/java.util.Formatter.format(Formatter.java:2688)
    at java.base/java.io.PrintStream.format(PrintStream.java:1209)
    at java.base/java.io.PrintStream.printf(PrintStream.java:1105)
    at PrettyPrinting.main(PrettyPrinting.java:6)

Process finished with exit code 1

I have tried with the format specifier of doble also but the issue still doesn’t get resolved and a different stack trace of Exception appears in the console. The error appears even without explicit typecasting.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have a typo in the 2nd printf().

float a = 453.1274f;
System.out.printf(Locale.ENGLISH, "Formatted number is %.2f \n", a);
System.out.printf(Locale.ENGLISH, "Pi is: %.3f\n", Math.PI);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading