Java Reference
In-Depth Information
The NumberFormat class provides numeric formatting functions; however, you cannot instantiate an object of
type NumberFormat . Instead, the getInstance method, which returns a NumberFormat object, is used. The following is
an example of the syntax:
NumberFormat nf = NumberFormat.getInstance();
Of course, the NumberFormat class must also be imported as follows:
import java.text.NumberFormat;
Once the number formatter has been created, you can modify its formatting properties. For example, the
following sets the number of displayed decimal digits to 2.
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
If you now used nf to format numbers, they would be rounded to two decimal digits. For instance, the following
statements:
System.out.println(nf.format(10/3));
System.out.println(nf.format(34.565));
System.out.println(nf.format(34.5651));
Would result in the following values being displayed:
3.00
34.56
34.57
You may be a little surprised by the results. Note that the first calculation is between two integers so the result is
truncated to 3 before the formatter even gets the results. The next two numbers demonstrate the formatter's rounding
feature. Any fractional value of .5 or lower (beyond the maximum number of digits) is rounded down. In this example,
the second number's fractional value beyond the 2 fractional digits is .5 but the third number's is .51. So the first
number is truncated (or rounded down) and the second is rounded up.
Another very useful formatter is the currency formatter. Once again, use the NumberFormat class to create and
return an instance as follows:
NumberFormat cf = NumberFormat.getCurrencyInstance();
If we then formatted and displayed the following two numbers:
System.out.println(cf.format(34.565));
System.out.println(cf.format(34.5651));
The results would be:
$34.56
$34.57
 
Search WWH ::




Custom Search