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.
>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);