Java Reference
In-Depth Information
places should be up to three, padded with blanks if the fraction needs less than
three places.
An exponential pattern appends
“E0
„
to the right side. So
“0.000E0
„
results in three decimal places in the significand and then an exponent, such
as
“1.234E10
„
. See the Java 2 API specifications for
DecimalFormat
to find
the complete set of formatting pattern symbols.
The recipe for formatting a floating-point value goes as follows. First specify
a string pattern such as
String fmt
="
0.00#
"
;
Then create an instance of the
DecimalFormat
class with this pattern:
DecimalFormat df
=
new DecimalFormat (fmt);
Invoke the
format()
method to create a formatted string:
double q = 10.0/4.0;
String str = df.format (q);
System.out.println ("q ="+ str);
In this case the resulting string is:
q = 2.50
The
DecimalFormat
object can be reused for new format patterns by invok-
ing the
applyPattern (String format)
method. The following snippet
from the program
DecimalFormatDemo
illustrates several format patterns for
floating-point output:
...
code segment in
DecimalFormatDemo
...
double q
=
1.0/3.0;
// Define the format pattern in a string
String fmt
="
0.000
"
;
// Create a DecimalFormat instance for this format
DecimalFormat df = new DecimalFormat (fmt);
// Create a string from the double according to the
// format
valStr = df.format (q);
System.out.println ("1.0/3.0 ="+ valStr);
// Can change the format pattern:
df.applyPattern ("0.00000");
Search WWH ::
Custom Search