/* TestFormatting.java CIS 160 David Klick 2015-09-02 Demonstration of three different ways of creating formatted numeric output. */ import java.text.DecimalFormat; public class TestFormatting { public static void main(String[] args) { double number = 123.45678; String preamble = "The number is: "; String msg, tmp; // Display using printf // %s substitues in a String value // %6.2f substitutes in a fp value, 6 wide, two decimal positions // %n is a newline System.out.printf("%s%6.2f%n", preamble, number); // Display string created using String.format msg = String.format("%s%6.2f%n", preamble, number); System.out.print(msg); // Create a DecimalFormat object // Note: Please don't use DecimalFormat. It's too complicated. DecimalFormat twoDigits = new DecimalFormat("###.##"); tmp = twoDigits.format(number); System.out.println(preamble + tmp); } } /* Sample output: The number is: 123.46 The number is: 123.46 The number is: 123.46 */