1. Home
  2. Computing & Technology
  3. Java
photo of Paul Leahy
Paul's Java Blog

By Paul Leahy, About.com Guide to Java

Answer to Monday's Formatting Question

Sunday January 11, 2009

This week the programming task was focused on creating formatted Strings using the System.out.printf method.

More specifically you had to use the printf method to create formatted strings that display Math.PI to:

  • match the output of
    System.out.println(Math.PI);
  • only have two decimal places
  • have two decimal places and a positive sign (i.e., "+")
  • make the calculation of 1-Math.PI have two decimal places and a negative sign (i.e,"-")
  • have three leading zeros

And finally, to display the number 1234 as a denary number, a hexadecimal number, an octal number and finally as a denary number with five leading spaces.

Here's my version:

public class Formatting {

  public static void main(String[] args) {
    System.out.println(Math.PI);

    //printf defaults to 6 decimal places
    //so to match println command it needs
    //15 decimal places
    System.out.printf("%.15f%n", Math.PI);

    //two decimal places
    System.out.printf("%.2f%n", Math.PI);

    //two decimal places with positive sign
    System.out.printf("%+.2f%n", Math.PI);

    //two decimal places with negative sign
    System.out.printf("%+.2f%n", 1-Math.PI);

    //add three leading zeros
    System.out.printf("%011f%n", Math.PI);

    //decimal
    System.out.printf("%d%n",1234);

    //hexadecimal
    System.out.printf("%x%n",1234);

    //octal
    System.out.printf("%o%n",1234);

    //add leading five spaces
    System.out.printf("% 9d%n",1234);
  }
}
Comments

No comments yet. Leave a Comment

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Discuss
Community Forum
Explore Java
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Java

©2009 About.com, a part of The New York Times Company.

All rights reserved.