Java Reference
In-Depth Information
To perform more advanced formatting, you can use the
DecimalFormat
class. It allows you to supply your own
format pattern. Once you create an object of the
DecimalFormat
class, you can change the format pattern using its
applyPattern()
method. You can specify different patterns for positive and negative numbers. The two patterns are
separated by a semicolon. The
DecimalFormat
class uses round-to-even rounding mode while formatting numbers.
For example, if you have specified only two digits after the decimal point in your number format, 12.745 will be
rounded to 12.74, because 4 is even; 12.735 will also be rounded to 12,74; and 12.746 will be rounded to 12.75. You
can also parse a string to a number using the
parse()
method. Note that the
parse()
method returns an object of the
java.lang.Number
class. You can use
xxxValue()
methods to get the primitive value, where
xxx
can be
byte
,
double
,
float
,
int
,
long
, and
short
.
Listing 13-4 illustrates the use of the
DecimalFormat
class. Note that you can also use the
parseDouble()
method
of the
java.lang.Double
class to parse a string into a
double
value. However, the string has to be in the default
number format. The advantage of using the
parse()
method of the
DecimalFormat
class is that the string can be in
any format.
Listing 13-4.
Formatting and Parsing Numbers
// DecimalFormatter.java
package com.jdojo.format;
import java.text.ParsePosition;
import java.text.DecimalFormat;
public class DecimalFormatter {
private static DecimalFormat formatter = new DecimalFormat();
public static void main (String[] args){
formatNumber("##.##", 12.745);
formatNumber("##.##", 12.746);
formatNumber("0000.0000", 12.735);
formatNumber("#.##", -12.735);
// Positive and negative number format
formatNumber("#.##;(#.##)", -12.735);
// Parse a string to decimal number
String str = "XY4,123.983";
String pattern = "#,###.###";
formatter.applyPattern(pattern);
// Create a ParsePosition object to specify the first digit of
// number in the string. It is 4 in "XY4,123.983"
// with the index 2.
ParsePosition pp = new ParsePosition(2);
Number numberObject = formatter.parse(str, pp);
double value = numberObject.doubleValue();
System.out.println("Parsed Value is " + value);
}
public static void formatNumber(String pattern, double value) {
// Apply the pattern
formatter.applyPattern ( pattern );