Java Reference
In-Depth Information
The getVal() and setVal() are examples of the common getter and setter
methods used to get and set the value of a particular variable whose name is
included in the method name. In this way we follow the important JavaBeans
standard although the use of JavaBeans is not important to this topic. We also
note that the consistent use of the fMemberVariable notation for member
variables and local - variable - name notation for local variables inside a
method makes it impossible to accidentally shadow a member variable with a
local variable (see brief discussion on shadowing in Chapter 4).
5.11 Formatting numbers
Until recently Java separated I/O from the formatting. By formatting we mean
converting a number to a string in a specific form. A typical example is to specify
afixed number of decimal places to a floating-point value. Since strings were
usually intended for graphical displays such as labels and text fields (we discuss
Java graphics in Chapters 6 and 7), the procedure was to format a string in one
operation and then in a second operation send the formatted string to where it
wastobedisplayed. However, J2SE 5.0 provides the means both to format and
send data to a file or stream at the same time. Here we give a brief introduction
first to the older formatting approach and then to the new 5.0 techniques.
5.11.1 Format , NumberFormat , and DecimalFormat
Number formatting techniques available as of Java 1.4 and earlier are still use-
ful and commonly found in Java programs. In many of the previous demon-
stration programs, we often found that a simple floating-point operation such
as division could result in a long fraction when we used the default conver-
sion of a double value to a string. Control of the format for a numerical
value to string conversion was added in Java 1.1 with the java.text pack-
age. This package includes the abstract class java.text.Format ,which is
subclassed by java.text.NumberFormat . This class is in turn subclassed by
java.text.DecimalFormat .
These classes focus primarily on internationalization of numerical output such
as using either a period or comma for the decimal point according to the current
locale setting. (See the tutorial on internationalization of formatting given in the
reference [4].) However, scientific notation was added to DecimalFormat with
Java 1.2.
The approach of DecimalFormat is to specify the format with a pattern of
symbols. For example, the pattern “0.000 indicates that the number should
begin with 0 if it is less than 1.0 and that the number of decimal places should
be three and padded with 0 if necessary. The pattern “0.### indicates that the
number should begin with 0 if it is less than 1.0 and that the number of decimal
Search WWH ::




Custom Search