Java Format Justifying Output

Description

By default, all output is right-justified. You can force output to be left-justified by placing a minus sign directly after the %.

Syntax

fmt.format("|%#d|", 123.123);

or

fmt.format("|%#.#d|", 123.123);

Example

For instance, %-10.2f left-justifies a floating-point number with two decimal places in a 10-character field.


import java.util.Formatter;
// ww  w. j  a  va 2 s . c om
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    // Right justify by default
    fmt.format("|%10.2f|", 123.123);
    System.out.println(fmt);
    // Now, left justify.
    fmt = new Formatter();
    fmt.format("|%-10.2f|", 123.123);
    System.out.println(fmt);
  }
}

The output:

Example 2

Use Formatter to left-justify strings within a table


import java.util.Formatter;
// w ww. j a v  a 2  s.  co  m
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();

    fmt.format("%-12s %12s\n\n", "Source", "Loss");
    fmt.format("%-12s %,12d\n", "Retail", 1232675);

    System.out.println(fmt);
  }
}

The code above generates the following result.

Example 3

Use Formatter to vertically align numeric values


import java.util.Formatter;
/*  w w  w . j a  v a  2  s . c o m*/
public class Main {
  public static void main(String[] argv) throws Exception {
    double data[] = { 12.3, 45.6, -7.89, -1.0, 1.01 };
    Formatter fmt = new Formatter();

    fmt.format("%12s %12s\n", "Value", "Cube Root");

    for (double v : data) {
      fmt.format("%12.4f %12.4f\n", v, Math.cbrt(v));
    }
    System.out.println(fmt);
  }
}

The code above generates the following result.


       Value    Cube Root/*from w  w  w.j  a v  a 2s  .c o m*/
     12.3000       2.3084
     45.6000       3.5726
     -7.8900      -1.9908
     -1.0000      -1.0000
      1.0100       1.0033

Example 4


public class Main {
  public static void main(String args[]) {
    String format = "|%1$-10s|%2$10s|%3$-20s|\n";
    System.out.format(format, "A", "AA", "AAA");
    System.out.format(format, "B", "", "BBBBB");
    System.out.format(format, "C", "CCCCC", "CCCCCCCC");
/*from  w w w .ja  v a  2s.c om*/
    String ex[] = { "E", "java2s.com", "E" };

    System.out.format(String.format(format, (Object[]) ex));
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Data Format »




Java Formatter
Java Number Formatter