Java Reference
In-Depth Information
For example,
DecimalFormat formattingObject = new DecimalFormat("000.000");
The method format of the class DecimalFormat can then be used to convert
a floating-point number, such as one of type double , to a corresponding numeral
String following the Pattern used to create the DecimalFormat object. Specifically, an
invocation of format takes the form
Decimal_Format_Object .format( Double_Expression )
which returns a String value for a string representation of the value of Double_
Expression . Double_Expression can be any expression, such as a variable or sum of
variables, that evaluates to a value of type double .
For example, consider the following code:
DecimalFormat formattingObject = new DecimalFormat("000.0000");
String numeral = formattingObject.format(12.3456789);
System.out.println(numeral);
This produces the following output:
012.3457
Of course, you can use an invocation of format , such as formattingObject.format
(12.3456789) , directly in System.out.println . So, the following code produces the
same output:
System.out.println(formattingObject.format(12.3456789));
The format of the string produced is determined by the Pattern string that was used
as the argument to the constructor that created the object of the class DecimalFormat .
For example, the pattern "000.0000" means that there will be three digits before the
decimal point and four digits after the decimal point. Note that the result is rounded
when the number of digits is less than the number of digits available in the number
being formatted. If the format pattern is not consistent with the value of the number,
such as a pattern that asks for two digits before the decimal point for a number such as
123.456 , then the format rules are violated so that no digits are lost.
A pattern can specify the exact number of digits before and after the decimal, or
it can specify minimum numbers of digits. The character '0' is used to represent a
required digit, and the character '#' is used to indicate an optional digit. For example,
the pattern "#0.0##" indicates one or two digits before the decimal point and one,
two, or three digits after the decimal point. The optional digit '#' is shown if it is a
nonzero digit and is not shown if it is a zero digit. The '#' optional digits should go
where zero placeholders would appear in a numeral string; in other words, any '#'
optional digits precede the zero digits '0' before the decimal point in the pattern, and
Search WWH ::




Custom Search