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);
        int accountNumber = 30310;
        double accountBalance = 47927.32;
            accountNumber, accountNumber, accountNumber, accountNumber,
            accountBalance, accountBalance, accountBalance, accountBalance);    

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


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.

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

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App