It is often necessary to print values with a designated number of decimal
places. For example, when printing amounts of money, it is customary to
have two decimal places printed to the right of the decimal point. The
money amounts of $15.1 and $53.9 are more commonly seen as
$15.10 and $53.90.
To insure that a designated number of decimal places will be printed, we will
need to utilize the Decimal Format Class.
It will be necessary to include:
import
java.text.*;
You will need to create an object
of the class DecimalFormat using a String pattern.
DecimalFormat
variable_name = new DecimalFormat("000.000");
The String pattern will designate how your
display will look. The number of zeros in front of the decimal point will
be the minimum number of locations printed to the left of the decimal. The
number of zeros behind the decimal point will be the maximum number of locations
printed to the right of the decimal. With the pattern shown above, the
number 45.66844 would print as 045.668.
Sample program:
import java.io.*;
import java.text.*;
public class DecimalTest
{
public static void main(String[ ] args)
{
double money =
15.9;
double mula =
36.56789;
DecimalFormat
decFor = new DecimalFormat("0.00");
System.out.println(decFor.format(money)+"\n"+
decFor.format(mula));
}
}
|
Screen
output: 15.90
36.57
 |
|