Floating-point number formatting formats numbers with a whole part and a fraction part.

It can be applied to format values of float, Float, double, Double, and BigDecimal data types.

The following table lists conversions used for formatting floating-point number formatting.

Conversion | Uppercase Variant | Description |
---|---|---|

'e' | 'E' | formats the argument in a locale-specific scientific notation, for example, 1.832123e+03. 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. Precision is 6 By default. |

'f' | n/a | 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 depending on the conversion character.

The precision is 6 by default.

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 code shows how to format floating-point numbers with the default precision, which is 6:

public class Main { public static void main(String[] args) {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); }// w ww . j a v a 2s . c o m }