Java Reference
In-Depth Information
You can use the Java
class
DecimalFormat
to format decimal numbers in a specific
manner. The method
format
of the
class
DecimalFormat
is applied to the decimal
value being formatted. The following steps explain how to use these features to format
decimal numbers:
1. Create a
DecimalFormat
object and initialize it to the specific format. Consider the
following statement:
DecimalFormat twoDecimal =
new
DecimalFormat("0.00");
This statement creates the
DecimalFormat
object
twoDecimal
and initializes it to
the string
"0.00"
. Each
0
in the string is a format flag. The string
"0.00"
specifies
the formatting of the decimal number. This string indicates that the decimal number
being formatted with the object
twoDecimal
will have at least one digit to the left
of the decimal point and exactly two digits to the right of the decimal point. If the
number being formatted does not meet the formatting requirement, that is, it does
not have digits at the specified places, those places are automatically filled with 0.
Moreover, suppose that you have the following statement:
DecimalFormat twoDigits =
new
DecimalFormat("0.##");
The object
twoDigits
can be used to format the number with two decimal places,
but the
##
symbols indicate that trailing zeros will appear as spaces.
2. Next, use the method
format
of the
class
DecimalFormat
. (Assume the first
declaration of Step 1.) For example, the statement:
twoDecimal.format(56.379);
formats the decimal number
56.379
as
56.38
(the decimal number is rounded).
The method format returns the string containing the digits of the formatted number.
3. The
class
DecimalFormat
is included in the
package
java.text
. You must
import this
class
into your program.
Example D-2 illustrates how to format the output of decimal numbers.
EXAMPLE D-2
//Program: Formatting output of decimal numbers using
//the class DecimalFormat
import
java.text.DecimalFormat;
public class
FormattingDecimalNum
{
public static void
main(String[] args)
{
double
x = 15.674;
//Line 1
double
y = 235.73;
//Line 2
double
z = 9525.9864;
//Line 3
Search WWH ::
Custom Search