Which of the following will format 12.78 to display as 12.8%?

Java
Question 12 Which of the following will format 12.78 to display as 12.8%? System.out.printf(*2.ldt, 12.78); System.out.prin

Answer

Answer is :

 System.out.printf("%.1f%%", 12.78);

Output:

Output: 12.8%

It will print 12.78 as
12.8%.Here
% as a special character you need to add, so it
can know, that when you type “f”, the number (result) that will be
printed will be a floating point type, and the “.1” tells your
“printf” to print only the first 1 digit after the
point(rounded).And extra % will print with 12.8 as 12.8%.

But these are not answers
because:

1.

 System.out.printf("%2.1d%", 12.78);

Runtime
Error:

Exception in thread "main" java.util.IllegalFormatPrecisionException: 1   at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2984)        at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2729)        at java.util.Formatter.parse(Formatter.java:2560)

Output:

Output: No Output

2.

 System.out.printf("%.2f%%", 12.78);

Output:

Output: 12.78%

Here same as above but 2 digits after the decimal places
(rounded) because of 0.2f.

3.

 System.out.printf("%1.2d%", 12.78);

Runtime
Error:

Exception in thread "main" java.util.IllegalFormatPrecisionException: 2  at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2984)        at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2729)        at java.util.Formatter.parse(Formatter.java:2560)

Output:

Output: No Output

Leave a Comment