go to previous page   go to home page   go to next page highlighting

Answer:

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.


Conversion Codes

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
bbooleantrue
ccharacterB
dinteger (output as decimal)221
ointeger (output as octal)335
xinteger (output as hex)dd
ffloating point45.356
efloating point (scientific notation)-8.756e+05
sStringHello World
nnewline

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:


QUESTION 4:

Would the following program fragment work?

int size = 7;
System.out.printf("Perfect: %8.3f %n", size );

go to previous page   go to home page   go to next page