Open In App

NumberFormat Class in Java

NumberFormat is an abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales (US, India, Italy, etc.) have number formats and their names. NumberFormat helps you to format and parse numbers for any locale. 

Example: Suppose we have a double type number. But this double type number is represented in different ways in different countries. To represent a number according to various countries, we have to take the help of NumberFormat class like: 



double d = 123456.789;
For India, it is represented like 1,23,456.789
For US, it is represented like 123,456.789
For ITALY, it is represented like 123.456,789

Some Important Points About NumberFormat Class: 

Methods Present in NumberFormat Class

S. No. Method Description
1. public static NumberFormat getInstance() To get the NumberFormat object for default Locale.
2. public static NumberFormat getCurrencyInstance() To get the NumberFormat object for default Locale to represent in specific Currency.
3. public static NumberFormat getPercentInstance() The function accepts a single mandatory parameter inLocale which describes the locale which is to be specified.
4. public static NumberFormat getInstance(Locale l) To get the NumberFormat object for the specified Locale object.
5. public static format(long l) To convert java number to locale object.

Example:






// Java Program to illustrate NumberFormat class use
 
import java.text.*;
import java.util.*;
 
class NumberFormatDemo {
    public static void main(String[] args)
    {
        double d = 123456.789;
        NumberFormat nf
            = NumberFormat.getInstance(Locale.ITALY);
        System.out.println("ITALY representation of " + d
                           + " : " + nf.format(d));
    }
}

Output
ITALY representation of 123456.789 : 123.456,789
Article Tags :