Number Format Example

This Example shows you how to format numbers according to the locale. In the code given below we are formatting number according to the locale

Number Format Example

Number Format Example

     

This Example shows you how to format numbers according to the locale. In the code given below we are formatting number according to the locale

Methods used in this example are described below :

NumberFormat.getNumberInstance() : NumberFormat class provides the functionality for formatting and parsing numbers. NumberFormat class also provides methods for defining which locales have number formats.

NumberFormat.format() : This method returns a format string of a number.

NumberFormatExample.java

import java.text.*;
import java.util.*;

class NumberFormatExample {

  public void numberFormat(Locale currentLocale) {
  Integer intNum = new Integer(123456789);
  Double doubleNum = new Double(1234.1234);

  String intNumOut, doubleNumOut;

  NumberFormat numberFormatter = 
  NumberFormat.getNumberInstance(currentLocale);

  intNumOut = numberFormatter.format(intNum);
  doubleNumOut = numberFormatter.format(doubleNum);

  System.out.println();
  System.out.println("Integer num : " + intNumOut + 
  " " + currentLocale.toString());

  System.out.println("Double  num : " + doubleNumOut + 
  " " + currentLocale.toString());

  }

  public static void main(String args[]) {
  Locale[] locales = new Locale[]{new Locale
  ("fr""FR")new Locale("de""DE"),

  new Locale("ca""CA"),new Locale("rs""RS"),
  new Locale("en""IN")
  };

  NumberFormatExample[] formate = new 
  NumberFormatExample[locales.length];

  for (int i = 0; i < locales.length; i++) {
  formate[inew NumberFormatExample();
  formate[i].numberFormat(locales[i]);

  }
  }
}


Output :


Integer num : 123 456 789 fr_FR
Double  num : 1 234,123 fr_FR

Integer num : 123.456.789 de_DE
Double  num : 1.234,123 de_DE

Integer num : 123.456.789 ca_CA
Double  num : 1.234,123 ca_CA

Integer num : 123,456,789 rs_RS
Double  num : 1,234.123 rs_RS

Integer num : 123,456,789 en_IN
Double  num : 1,234.123 en_IN

Download code