double value = 123456.120001; System.out.printf("value =%5.2f", value);
value =123456.12
Way more than a width of 5 was used to format the number.
If the field width is too small for the integer part of the value,
printf()
uses more spaces
than you asked for.
That way the value printed is correct, although not nicely formatted.
However, the number of digits used for the precision is the number you asked for. This could be dangerous when printing small numbers like 0.0000034.
To print a percent sign, use two percent signs in a row:
double finalGrade = 97.45; System.out.printf("Grade: %4.1f%%", finalGrade);
Output:
Grade: 97.5%
Here are some additional conversion codes. Only floating point types use the precision part of a format specifier.
Conversion Code | Type | Example Output |
---|---|---|
b | boolean | true |
c | character | B |
d | integer (output as decimal) | 221 |
o | integer (output as octal) | 335 |
x | integer (output as hex) | dd |
f | floating point | 45.356 |
e | floating point (scientific notation) | -8.756e+05 |
s | String | Hello World |
n | newline |
The example program uses some of these conversion codes in its format specifiers:
public class ConvCodes { public static void main ( String[] args ) { boolean r = true; char b = 'B'; int adrs = 221; long date = 1666; double x = -875612.0014; String fire = "Great Fire:"; System.out.printf("Roses are Red:%10b%n", r); System.out.printf("Answer to Question 1:%5c%n", b); System.out.printf("Sherlock Lived at:%3d%c%n", adrs, b); System.out.printf("%s %d%n", fire, date); System.out.printf("Usual format: %8.3f Scientific format: %8.3e%n", x, x); } }
Here is the output:
Roses are Red: true Answer to Question 1: B Sherlock Lived at:221B Great Fire: 1666 Usual format: -875612.001 Scientific format: -8.756e+05
Notes:
float
and double
short
, int
, and long
Would the following program fragment work?
int size = 7; System.out.printf("Perfect: %8.3f %n", size );