To send formatted outputs directly to a string, the class provides
several overloaded format(arg)
methods, where arg
is a number type. An instance of the format must first be created
with the desired formatting description.
This can be done in a convenient single line approach by appending
the method invocation to the instantiation operation as shown
here:
double
q =10.0/3.0;
String str = new Format("0.3e").format(q)
which results in the string variable str
referencing "3.333e+000".
The following applet illustrates how the previous demo
would change if Format is used.
|
CJ_applet7.java |
... code
segment ...
double
q = 1.0/3.0;
// Create an instance of the format
pattern
// and then create the string with
the method format
qValStr = new Format ("%0.3f").format
(q);
System.out.println ("1.0/3.0 = "
+ qValStr);
// Can change the format pattern:
qValStr = new Format ("%0.5f").format
(q);
System.out.println ("1.0/3.0 = "
+ qValStr);
// The # symbol indicates trailing
blanks
q = 1.0/2.0;
qValStr = new Format ("%0.5g").format
(q);
System.out.println ("1.0/2.0 = "
+ qValStr);
//
q = 1000.0/3.0;
qValStr = new Format ("%0.2e").format
(q);
System.out.println ("1000.0/3.0
= " + qValStr);
//
q = 3.0/4567.0;
qValStr = new Format ("%0.2e").format
(q);
System.out.println ("3.0/4567.0
= " + qValStr);
// Negative infinity
q = -1.0/0.0;
qValStr = new Format ("%0.3e").format
(q);
System.out.println ("-1.0/0.0 =
" + qValStr);
// NaN
q = 0.0/0.0;
qValStr = new Format ("%0.3e").format
(q);
System.out.println ("0.0/0.0 = "
+ qValStr);
.... rest
of the code ...
|
Output of this program:
1.0/3.0
= 0.333
1.0/3.0 = 0.33333
1.0/2.0 = 0.5
1000.0/3.0 = 3.33e+002
3.0/4567.0 = 6.57e-004
-1.0/0.0 = -Inf
0.0/0.0 = NaN
|
The following applet uses the Format
class to illustrate how to select the precision for the format
of floating point numbers.
We have not yet discussed how to program graphical
interfaces but you can look at this code for a preview.
Latest update: Oct. 25, 2004