Java Reference
In-Depth Information
// Format the number
String formattedNumber = formatter.format(value) ;
System.out.println("Number:" + value + ", Pattern:" +
pattern + ", Formatted Number:" +
formattedNumber);
}
}
Number:12.745, Pattern:##.##, Formatted Number:12.74
Number:12.746, Pattern:##.##, Formatted Number:12.75
Number:12.735, Pattern:0000.0000, Formatted Number:0012.7350
Number:-12.735, Pattern:#.##, Formatted Number:-12.73
Number:-12.735, Pattern:#.##;(#.##), Formatted Number:(12.73)
Parsed Value is 4123.983
Printf-style Formatting
In this section, I will discuss how to format objects and values using printf -style formatting similar to that supported
by the printf() function in C. First I will cover the general ideas of the printf -style formatting support in Java and
then the details of formatting all types of values.
The Big Picture
The java.util.Formatter class supports printf -style formatting, which is similar to the formatting supported by
the printf() function in C programming language. If you are familiar with C, C++, and C#, it should be easier for you
to understand the discussion in this section. In this section, you will use formatting strings such as "%1$s" , "%1$4d" ,
etc. in your code without explaining their meanings. You may not be able to understand them fully; you should ignore
them for now. Just focus on the output and try to get the bigger picture of what the Formatter class is intended to
accomplish, rather than trying to understand the details. I will discuss the details in the next section. Let's start with a
simple example shown in Listing 13-5. You may get a slightly different output.
Listing 13-5. Using C's Printf-style Formatting in Java
// PrintfTest.java
package com.jdojo.format;
import java.util.Date;
public class PrintfTest {
public static void main(String[] args) {
// Formatting strings
System.out.printf("%1$s, %2$s, and %3$s %n", "Fu", "Hu", "Lo");
System.out.printf("%3$s, %2$s, and %1$s %n", "Fu", "Hu", "Lo");
// Formatting numbers
System.out.printf("%1$4d, %2$4d, %3$4d %n", 1, 10, 100);
System.out.printf("%1$4d, %2$4d, %3$4d %n", 10, 100, 1000);
 
Search WWH ::




Custom Search