- Is used to control the formatting when you are converting
floats, ints, doubles, and longs to strings.
- To use a DecimalFormat object you must import its definition
using an import statement. The import statement should be one of the
first lines in the java file.
import java.text.*;
- To use a format object you must first declare and create
it. This can be done in one line. For a currency this would look
like.
DecimalFormat currency = new
DecimalFormat("$ #,##0.00");
- This line uses a pattern "$ #,##0.00" to specify what the
resulting number should look like when converted to a string. The "#"
character refers to a digit (0-9), leading 0's do not
appear. The "0"
character represents a digit (0-9) where leading and trailing 0's will
appear.
The "$ " will just be appear on front of the number. The "," characters
are
grouping separators and will only appear if a digit is present on each
side
of them, since the "," has three digits between it and the ".", then
"," would appear every three digits. In this example, a number
will always have a dollar sign and
at least 3 digits (one before and two after the decimal point).
Numbers are automatically rounded.
- Once the format object has been created, then it can be used
when converting numbers to strings using its format
method. For
example:
double salary = 29123.4403;
DecimalFormat
currency= new DecimalFormat("$ #,##0.00");
System.out.println("my salary is = " + salary); // show
salary unformatted
System.out.println("my salary is = " +
currency.format(salary)); // show salary formatted
- produces the output: