Formatting with printf

Nicholas Duchon: Mar 21, 2018.

Outline


Example:

// See class Formatter

public class PrintfExample {
public static void main (String args []) {
double pi = Math.PI;
System.out.println ("For details, see the java.util.Formatter class");
System.out.println ("Using println default: \n\t>" + pi + "<");
System.out.printf ("Using printf %%f - \n\t>%f<\n", pi);
System.out.printf ("Using printf %%.2f - \n\t>%.2f<\n", pi);
System.out.printf ("Using printf, formatting money $ %%(,.2f - \n\t>$ %(,.2f<\n", 1000000*pi);
System.out.printf ("Using printf, formatting money $ %%(,.2f - \n\t>$ %(,.2f<\n", -1000000*pi);

int x = 987654321;
System.out.println ("int's: 987654321");
System.out.println ("Using the println default: \n\t>" + x + "<");
System.out.printf ("Using printf %%d - \n\t>%d<\n", x);
System.out.printf ("Using printf %%,15d - \n\t>%,15d<\n", x);
System.out.printf ("Using printf %%o - \n\t>%o<\n", x);
System.out.printf ("Using printf %%x - \n\t>%x<\n", x);

System.out.println ("\nNegative int: -987654321");
System.out.printf ("Using printf %%d - \n\t>%d<\n", -x);
System.out.printf ("Using printf %%o - \n\t>%o<\n", -x);
System.out.printf ("Using printf %%x - \n\t>%x<\n", -x);
System.out.printf ("Using printf %%(d - \n\t>%(d<\n", -x);
} // end method main
} // end PrintfExample

Output:

For details, see the java.util.Formatter class
Using println default:
>3.141592653589793<
Using printf %f -
>3.141593<
Using printf %.2f -
>3.14<
Using printf, formatting money $ %(,.2f -
>$ 3,141,592.65<
Using printf, formatting money $ %(,.2f -
>$ (3,141,592.65)<

int's: 987654321
Using the println default:
>987654321<
Using printf %d -
>987654321<
Using printf %,15d -
> 987,654,321<
Using printf %o -
>7267464261<
Using printf %x -
>3ade68b1<

Negative int: -987654321
Using printf %d -
>-987654321<
Using printf %o -
>30510313517<
Using printf %x -
>c521974f<
Using printf %(d -
>(987654321)<

Notes:

 Some of the more useful features of Formatter, there are LOTS of others:


ND.