Tutorial Downloads .com

Home

Formatting Numeric Print Output

Earlier you saw the use of the print and println methods for printing strings to standard output (System.out). Since all numbers can be converted to strings (as you will see later in this lesson), you can use these methods to print out an arbitrary mixture of strings and numbers. The Java programming language has other methods, however, that allow you to exercise much more control over your print output when numbers are included.

Formatting Numeric Print Output
Earlier you saw the use of the print and println methods for printing strings to standard output (System.out). Since all numbers can be converted to strings (as you will see later in this lesson), you can use these methods to print out an arbitrary mixture of strings and numbers. The Java programming language has other methods, however, that allow you to exercise much more control over your print output when numbers are included.

The printf and format Methods

The java.io package includes a PrintStream class that has two formatting methods that you can use to replace print and println. These methods, format and printf, are equivalent to one another. The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out. Thus, you can use format or printf anywhere in your code where you have previously been using print or println. For example,
System.out.format(.....);

The syntax for these two java.io.PrintStream methods is the same:

public PrintStream format(String format, Object... args)
where format is a string that specifies the formatting to be used and args is a list of the variables to be printed using that formatting. A simple example would be
System.out.format("The value of the float variable is %f, while the value of the " + 
"integer variable is %d, and the string is %s", floatVar, intVar, stringVar);
The first parameter, format, is a format string specifying how the objects in the second parameter, args, are to be formatted. The format string contains plain text as well as format specifiers, which are special characters that format the arguments of Object... args. (The notation Object... args is called varargs, which means that the number of arguments may vary.)

Format specifiers begin with a percent sign (%) and end with a converter. The converter is a character indicating the type of argument to be formatted. In between the percent sign (%) and the converter you can have optional flags and specifiers. There are many converters, flags, and specifiers, which are documented in java.util.Formatter

Here is a basic example:

int i = 461012;
System.out.format("The value of i is: %d%n", i);
The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is:
The value of i is: 461012

The printf and format methods are overloaded. Each has a version with the following syntax:

public PrintStream format(Locale l, String format, Object... args)
To print numbers in the French system (where a comma is used in place of the decimal place in the English representation of floating point numbers), for example, you would use:
System.out.format(Locale.FRANCE, "The value of the float variable is %f, while the value of the " + 
"integer variable is %d, and the string is %s%n", floatVar, intVar, stringVar);

An Example

The following table lists some of the converters and flags that are used in the sample program, TestFormat.java, that follows the table.

Converters and Flags Used in TestFormat.java
Converter Flag Explanation
d   A decimal integer.
f   A float.
n   A new line character appropriate to the platform running the application. You should always use %n, rather than \n.
tB   A date & time conversion—locale-specific full name of month.
td, te   A date & time conversion—2-digit day of month. td has leading zeroes as needed, te does not.
ty, tY   A date & time conversion—ty = 2-digit year, tY = 4-digit year.
tl   A date & time conversion—hour in 12-hour clock.
tM   A date & time conversion—minutes in 2 digits, with leading zeroes as necessary.
tp   A date & time conversion—locale-specific am/pm (lower case).
tm   A date & time conversion—months in 2 digits, with leading zeroes as necessary.
tD   A date & time conversion—date as %tm%td%ty
  08 Eight characters in width, with leading zeroes as necessary.
  + Includes sign, whether positive or negative.
  , Includes locale-specific grouping characters.
  - Left-justified..
  .3 Three places after decimal point.
  10.3 Ten characters in width, right justified, with three places after decimal point.

The following program shows some of the formatting that you can do with format. The output is shown within double quotes in the embedded comment:

import java.util.Calendar;
import java.util.Locale;

public class TestFormat {

public static void main(String[] args) {
long n = 461012;
System.out.format("%d%n", n); // --> "461012"
System.out.format("%08d%n", n); // --> "00461012"
System.out.format("%+8d%n", n); // --> " +461012"
System.out.format("%,8d%n", n); // --> " 461,012"
System.out.format("%+,8d%n%n", n); // --> "+461,012"

double pi = Math.PI;
System.out.format("%f%n", pi); // --> "3.141593"
System.out.format("%.3f%n", pi); // --> "3.142"
System.out.format("%10.3f%n", pi); // --> " 3.142"
System.out.format("%-10.3f%n", pi); // --> "3.142"
System.out.format(Locale.FRANCE,
"%-10.4f%n%n", pi); // --> "3,1416"

Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006"
System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am"
System.out.format("%tD%n", c); // --> "05/29/06"
}
}

Note: The discussion in this section covers just the basics of the format and printf methods. Further detail can be found in the Basic I/O section titled "Formatting". Using String.format to create strings is covered in Strings.

The DecimalFormat Class

You can use the java.text.DecimalFormat class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. DecimalFormat offers a great deal of flexibility in the formatting of numbers, but it can make your code more complex.

The example that follows creates a DecimalFormat object, myFormatter, by passing a pattern string to the DecimalFormat constructor. The format() method, which DecimalFormat inherits from NumberFormat, is then invoked by myFormatter—it accepts a double value as an argument and returns the formatted number in a string:

Here is a sample program that illustrates the use of DecimalFormat:

/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.text.*;

public class DecimalFormatDemo {

static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}

static public void main(String[] args) {

customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}

The output is:

123456.789  ###,###.###  123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67

The following table explains each line of output.

DecimalFormat.java Output
Value Pattern Output Explanation
123456.789 ###,###.### 123,456.789 The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator.
123456.789 ###.## 123456.79 The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up.
123.78 000000.000 000123.780 The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#).
12345.67 $###,###.### $12,345.67 The first character in the pattern is the dollar sign ($). Note that it immediately precedes the leftmost digit in the formatted output.


Resource: http://java.sun.com/docs/books/tutorial/java/data/numberformat.html
Posted By : Richard
On date : 05.28.08

Most used JAVA Tutorials

JAVA Tutorials ( Ebooks , PDF's )
Java Code Conventions Java and C++ A critical comparison Generics in the Java Programming Language Writing Robust Java Code
Brewing Java: A Tutorial
Part 1 is a brief introduction to what Java is, why it's cool and what you need to use it. Part 2 is a tutorial introduction to Java that just covers what you need to know to start programming command line applications in Java. This is an introduction to the basic syntax of the language. It skims over many details and completely omits little used features like bit-shift operators. This section is fairly complete. Part 3 covers the basics of writing applets in Java. Part 4 introduces you to objects and classes.
JAVA Interview Questions & Answers
What is a transient variable, Why do threads block on I/O, How are Observer and Observable used, What is synchronization and why is it important, Can a lock be acquired on a class, What is the Collections API,What is the List interface, What is the Vector class, What is an Iterator interface, What is the difference between yielding and sleeping, What are wrapper classes, What is the difference between preemptive scheduling and time slicing, What is clipping, What class is the top of the AWT event hierarchy, What is the purpose of the wait(), notify(), and notifyAll() methods ... etc... etc...
Struts interview Questions and answers | FAQs
Interview questions and answers of Struts
The java.util.concurrent package Collections
The java.util.concurrent package includes a number of additions to the Java Collections Framework.
JAVA PDF Tutorials, Code Conventions, Writing Robust Java Code
Java Code Conventions,Java and C++ A critical comparison,Generics in the Java Programming Language,Writing Robust Java Code
JFreeChart Introduction
JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications. JFreeChart's extensive feature set includes:
SCJP Sun Certified Programmer for Java 6 Exam 310-065 - Tutorial book
With hundreds of practice questions and hands-on exercises, SCJP Sun Certified Programmer for Java 6 Study Guide covers what you need to know--and shows you how to prepare--for this challenging exam.
NetBeans, Java, and JFreeChart | PDF study material
This set of “papers” consists of an introduction to JFreeChart and NetBeans as an IDE for Java programming. I attempt herein to ease the learning burden, a little, compared to the misery that I had to suffer through. We are using JDK 1.5.0_03, NetBeans 4.1 (for future work, we've gone over to 5.0), and jfreechart-1.0.0-rc1. I hope its not necessary to mention that all of these programs are free, in the public domain, and can be downloaded and installed on modern PCs.
JSF and Struts Classic Reference Manual | Pdf study material
The following chapters describe how to deal with classic/old style of JSF and Struts development. We recommend users to use JBoss Seam [http://www.redhat.com/developers/jbds/Getting_Started/GetStartSeamGen.html] to simplify development, but until then you can read about classical JSF and Struts usage here.We are going to show you how to create a simple JSF application using the JBoss Developer Studio plug-in for Eclipse.
Effective Java (2nd Edition) - Java Book
Are you looking for a deeper understanding of the Java™ programming language so that you can write code that is clearer, more correct, more robust, and more reusable? Look no further! Effective Java™, Second Edition, brings together seventy-eight indispensable programmer’s rules of thumb: working, best-practice solutions for the programming challenges you encounter every day.
Java Interface User Guide (JAVA PDF)
This Java tutorial covers the details of Java Interface User Guide.An Introduction to the Java Interface The Datalogics Java Interface provides a Java-language wrapper to the Adobe PDF Library to facilitate the rapid creation of PDF documents via Java calls. The Adobe PDF Library is C-based, not Java-sourced, but as it is usable by any application type which supports calls to a C-based library, the Datalogics Java Interface has been created.
Java Technology - What java does? - How java works
Java technology is both a programming language and a platform. In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes - the machine language of the Java Virtual Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.
Executor Interfaces in JAVA
The java.util.concurrent package defines three executor interfaces: Executor, a simple interface that supports launching new tasks. ExecutorService, a subinterface of Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself.
BASIC CONCEPTS LESSON-1 JAVA OVERVIEW (JAVA PDF)
This Java tutorial covers the details of BASIC CONCEPTS LESSON-1 JAVA OVERVIEW (JAVA PDF).Before you can start writing Java programs, you need acquire and set up some kind of Java programming software.

Latest added JAVA Tutorials

TDD and Acceptance TDD for Java Developers tutorial book
Learn hands-on to test drive Java code How to avoid common TDD adoption pitfalls Acceptance test driven development and the Fit framework How to test Java EE components-Servlets, JSPs, and Spring Controllers
Java Concurrency in Practice - Book
Threads are a fundamental part of the Java platform. As multicore processors become the norm, using concurrency effectively becomes essential for building high-performance applications. Java SE 5 and 6 are a huge step forward for the development of concurrent applications, with improvements to the Java Virtual Machine to support high-performance, highly scalable concurrent classes and a rich set of new concurrency building blocks. In Java Concurrency in Practice, the creators of these new facilities explain not only how they work and how to use them, but also the motivation and design patterns behind them.
SCJP Sun Certified Programmer for Java 6 Exam 310-065 - Tutorial book
With hundreds of practice questions and hands-on exercises, SCJP Sun Certified Programmer for Java 6 Study Guide covers what you need to know--and shows you how to prepare--for this challenging exam.
Head First Design Patterns - Java tutorial Book
At any given moment, somewhere in the world someone struggles with the same software design problems you have. You know you don't want to reinvent the wheel (or worse, a flat tire), so you look to Design Patterns--the lessons learned by those who've faced the same problems. With Design Patterns, you get to take advantage of the best practices and experience of others, so that you can spend your time on... something else. Something more challenging. Something more complex. Something more fun.
Effective Java (2nd Edition) - Java Book
Are you looking for a deeper understanding of the Java™ programming language so that you can write code that is clearer, more correct, more robust, and more reusable? Look no further! Effective Java™, Second Edition, brings together seventy-eight indispensable programmer’s rules of thumb: working, best-practice solutions for the programming challenges you encounter every day.
Head First Java, 2nd Edition - Java Book
It has taken four years, but with Head First Java the introductory Java book category has finally come of age. This is an excellent book, far more capable than any of the scores of Java-for-novices books that have come before it. Kathy Sierra and Bert Bates deserve rich kudos--and big sales--for developing this book's new way of teaching the Java programming language, because any reader with even a little bit of discipline will come away with true understanding of how the language works. Perhaps best of all, this is no protracted "Hello, World" introductory guide. Readers get substantial exposure to object-oriented design and implementation, serialization, neatwork programming, threads, and Remote Method Invocation (RMI).
Learn how to load, validate and submit forms in Ext JS
This tutorial focuses on the topic of 'Processing Forms'. The journey will include client-side and server-side ?eld validation, form loading, submission, ?eld customization, and layout techniques that will make it a breeze to build great-looking and friendly forms.
Useful Apache Maven Plugins
This tutorial discusses some of the Maven plugins, both from Apache Maven and Codehaus Mojo project which are of great help to Maven builds.
while - Java Term
Details about the Java term while
volatile - Java Term
Details about the Java term volatile