CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Data

Data
Working with data types
The NumberFormat class

The NumberFormat class

java.text.NumberFormat

Three static methods of the NumberFormat class

Method Returns a NumberFormat object that has the
getCurrencyInstance() Default currency format ($99,999.99).
getPercentInstance() Default percent format (99%).
getNumberInstance()Default number format (99,999.999).

Three methods of a NumberFormat object

Method Description
format(anyNumberType) Returns a String object that has the format specified by the NumberFormat object.
setMinimumFractionDigits(int) Sets the minimum number of decimal places.
setMaximumFractionDigits(int) Sets the maximum number of decimal places.

Two NumberFormat methods that are coded in one statement

String majorityString = NumberFormat. getPercentInstance().format(majority);

How to use the NumberFormat class

  • You can use one of the static methods to create a NumberFormat object. Then, you can use the methods of that object to format one or more numbers.
  • When you use the format method, the result is automatically rounded by using a rounding technique called half-even: The number is rounded up if the preceding digit is odd, but the extra decimal places are truncated if the preceding digit is even.
  • The NumberFormat class is in the java.text package, so you'll want to include an import statement when you use this class.

The currency format

double price = 11.575;
NumberFormat currency = NumberFormat.getCurrencyInstance();
String priceString = currency.format(price); // returns $11.58
The percent format
double majority = .505;
NumberFormat percent = NumberFormat.getPercentInstance();
String majorityString = percent.format(majority); // returns 50%

The number format with one decimal place

double miles = 15341.253;
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String milesString = number.format(miles); // returns 15,341.3
Previous | NumberFormat class | Math class | Integer and Double classs | Next