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

static NumberFormat getCurrencyInstance()

A static method that returns a NumberFormat object that formats currency values.

static NumberFormat getPercentInstance()

A static method that returns a NumberFormat object that formats percentages.

static NumberFormat getNumberInstance()

A static method that returns a NumberFormat object that formats basic numbers.

String format(number)

Returns a string that contains the formatted number.

void setMinimumFraction Digits(int digits)

Sets the minimum number of digits to display to the right of the decimal point.

void setMaximumFraction Digits(int digits)

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 getXxxInstance 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%.

tip.eps If your program formats several numbers, consider creating the NumberFormat object as a class variable. That way, the NumberFormat object is created when the program starts. Then you can use the NumberFormat object from any method in the program’s class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset