Java Reference
In-Depth Information
Table 13-6.
List of Conversions Applicable to float, Float, double, Double, and BigDecimal Data Types
Conversion
Uppercase
Variant
Description
'e'
'E'
It formats the argument in a locale-specific computerized scientific notation,
for example, 1.969919e+03. The output contains one digit followed by a decimal
separator, which is followed by exponent part. For example, 1969.919 will be
formatted as 1.969919e+03 if the precision is 6. Precision is the number of digits
after the decimal separator. The group separator flag ' ,' cannot be used with this
conversion.
'g'
'G'
It formats the argument in a locale-specific general scientific notation.
Depending on the value of the argument, it acts as 'e' conversion or 'f '
conversion. It applies rounding to the value of the argument depending on the
value of the precision.
If the value after rounding is greater than or equal to 10
-4
but less than 10
precision
,
it formats the value as if 'f ' conversion is used.
If the value after rounding is less than 10
-4
or greater than or equal to 10
precision
,
it formats the value as if 'e' conversion is used.
Note that the total number of significant digits in the result is equal to the value
of the precision. By default, precision of 6 is used.
'f'
It formats the argument in a locale-specific decimal format. Precision is the
number of digits after the decimal separator. The value is rounded depending on
the specified value of the precision.
'a'
'A'
It formats the argument in hexadecimal exponential form. It is not applicable to
the argument of
BigDecimal
type.
The general syntax for a format specifier for floating-point number formatting is
%<argument_index$><flags><width><.precision><conversion>
The precision has different meanings. The meanings depend on the conversion character. By default, the value
of precision is 6. For
'e'
and
'f'
conversions, the precision is the number of digits after the decimal separator. For the
'g'
conversion, the precision is the total number of digits in the resulting magnitude after rounding. Precision is not
applicable to the
'a'
conversion.
The following snippet of code shows how to format floating-point numbers with the default precision, which is 6:
System.out.printf("%e %n", 10.2);
System.out.printf("%f %n", 10.2);
System.out.printf("%g %n", 10.2);
System.out.printf("%e %n", 0.000002079);
System.out.printf("%f %n", 0.000002079);
System.out.printf("%g %n", 0.000002079);
System.out.printf("%a %n", 0.000002079);