Menu
Topics Index
...
`


More Utility Classes > Formatter >
Siva Nookala - 15 Apr 2016
Formatting of integers and floating point values can be done using %d and %f respectively. For formatting floating point values in scientific notation we can use %e. We can use %g format if we want the shortest of '%f' or '%e'.

Formatting Numbers Demo
import java.util.*;

class FormattingNumbersDemo
{
    public static void main(String arg[])
    {
        Formatter fmt = new Formatter();
        
        for(double i = 1000; i < 1.0e+10; i *= 100)
        {
            fmt.format("%g ", i);
        }
        System.out.println(fmt.out());
        fmt.close();
        
        int accountNumber = 30310;
        double accountBalance = 47927.32;
        System.out.printf("|%d|%8d|%5d|%3d|%n|%f|%5f|%3f|%15.2f|%n",
            accountNumber, accountNumber, accountNumber, accountNumber,
            accountBalance, accountBalance, accountBalance, accountBalance);    
    }
}
OUTPUT

1000.00 100000 1.00000e+07 1.00000e+09
|30310|   30310|30310|30310|
|47927.320000|47927.320000|47927.320000|       47927.32|

DESCRIPTION

Formatting the floating point types and print them in shortest form can be done using '%g' as shown above. Initially it uses '%f' for formatting, but as the size increases, it switches to '%e' for printing.

In the second part we are printing the account number and balance in various formats. As you can observe when the number is smaller than the width given, we are padding with spaces. Also note that we are using the printf method of String, with out using the Formatter. Both of them work similarly.

THINGS TO TRY
  • Change from '%g' to '%f' and later to '%e' and see the changes in the output.
  • Instead of double values, try printing integer values.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App