NumberFormat Class
Package: java.text
The NumberFormat
class provides methods that let you convert numeric values to strings with various types of numeric formatting applied.
Methods
Method |
Explanation |
|
A static method that returns a |
|
A static method that returns a |
|
A static method that returns a |
|
Returns a string that contains the formatted number. |
|
Sets the minimum number of digits to display to the right of the decimal point. |
|
Sets the maximum number of digits to display to the right of the decimal point. |
To use the NumberFormat
class to format numbers, you must first call one of the static get
XxxInstance
methods to create a NumberFormat
object that can format numbers in a particular way. Then, if you want, you can call the setMinimum FractionDigits
or setMaximumFractionDigits
method to set the number of decimal digits to be displayed. Finally, you call that object’s format
method to actually format a number.
Here’s an example that uses the NumberFormat
class to format a double
value as currency:
double salesTax = 2.425;
NumberFormat cf = NumberFormat.getCurrencyInstance();
String FormattedNumber = cf.format(salesTax);
When you run this code, the variable FormattedNumber
is set to the string $2.43
. Note that the currency format rounds the value from 2.425
to 2.43
.
Here’s an example that formats a number by using the general number format, with exactly three decimal places:
double x = 19923.3288;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(3);
nf.setMaximumFractionDigits(3);
String FormattedNumber = nf.format(x);
When you run this code, the variable FormattedNumber
is set to the string 19,923.329
. As you can see, the number is formatted with a comma, and the value is rounded to three places.
Here’s an example that uses the percentage format:
double grade = .92;
NumberFormat pf = NumberFormat.getPercentInstance();
String FormattedNumber = pf.format(grade);
When you run this code, FormattedNumber
is set to the string 92%
.