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(); ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.