NumberFormat In Java

NumberFormat formats and parses all the number in a specific locale or independent from the locale.

NumberFormat In Java

In this section we will read about the NumberFormat class in Java. Here we will read how this class helps in to format and parse the numbers.

NumberFormat class belongs to java.text packag. This class extends the Format class. NumberFormat is an abstract class, and it is acted as a parent class for all number formats. This class gives methods for specifying the locale specific number formats and their name. Using this class you can create your code independent from the locale specific for decimal points, thousand-separators etc.

This class provides various getter methods to get the number format in a specific format. For example getInstance or getNumberInstance is used to format normal number, getIntegerInstance to format integer number, getCurrencyInstance to format the currency number, getPercentInstance to format number into percentage.

This class also provides the setter method to set the minimum fraction digit using setMinimumFractionDigits, setMaximumFractionDigits, setMinimumIntegerDigits, setMaximumIntegerDigits.

In programming you can use the NumberFormat.getInstance().format(number) method to format the number for current locale.


Here an example is being given which will demonstrate you about how to format numbers. In this example I will create a Java class where I will try to format a number by setting the number of decimal places.

import java.text.NumberFormat;
public class NumberFormatExample {
  public static void main(String args[]) {
	 //get the NumberFormat object for current locale. 
    NumberFormat numberFormat = NumberFormat.getInstance();
    // setting number after decimal places
    // from integer to String
    String formatNumber = numberFormat.format(1234);
    // output will contain 000 after decimal
    System.out.println("1234 number formatted to " + formatNumber);
    formatNumber = numberFormat.format(123.45);
    System.out.println("123.45 number formatted to " + formatNumber);
    formatNumber = numberFormat.format(123.45);
    System.out.println("123.45 number formatted to " + formatNumber);
    numberFormat = NumberFormat.getPercentInstance();


When you will compile and execute the above example you will get the output as follows :

Download Source Code

Share on Google+Share on Google+

NumberFormat In Java

Posted on: August 10, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: NumberFormat In Java  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image