THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

  • f, Fdecimal format (such as 3.142)

  • g, Ggeneral scientific notation (see below)

  • a, Ahexadecimal exponential format (as used for hexadecimal floating-point literalssee page 168)


In each case a value of NaN or infinity produces the strings "NaN" or "Infinity".


The width value specifies the minimum number of characters to output, with the result being padded if
necessary to fit the requested width. For everything except general scientific conversion, the precision value
specifies the number of digits to output after the decimal point (or hexadecimal point), with the value rounded
as necessary to match that precision. If no precision is given then it defaults to 6, except for the hexadecimal
exponential form where no precision means to use as many places as needed.


A conversion to general scientific notation chooses the output format based on the magnitude of the value and
the precision that is given. In this case precision indicates the number of significant digits (not the number of
fractional digits). If after rounding to the specified precision, the value is smaller than 10-4, or it is greater than
or equal to 10precision, then computerized scientific notation is used; otherwise, decimal format is used. For
example, given


System.out.
printf("%1$.5g %1$.4g %1$.3g %1$.2g %n", Math.PI * 100);


The output is:


314.16 314.2 314 3.1e+02


You can see the value being rounded according to the number of significant digits requested, and see the
switch to scientific notation when the value exceeds 10^2.


For the general scientific notation conversion, if the precision is not given it defaults to 6, but a precision of
zero is treated as a precision of 1.


The flags applicable to each conversion are shown in the following table. An entry with x means the flag is
not allowed.


Flag e/E f/F g/G a/A Meaning

'-' Left justify (otherwise right justify)

'#' x Always include the (hexa)decimal point

'+' Always include the sign

' ' (space) Leading space for positive values

'0' Use zero-padding (else spaces)

',' x x Include grouping separators

'(' x Enclose negative values in parentheses

As with the integer conversions, you cannot use + and space together, nor can you use and 0 together. If
either of 0 or is given then a width must be given.

Free download pdf