NumberFormat class in Java


NumberFormat helps you to format and parse numbers for any locale. It is the abstract base class for all number formats.

Following are some of the methods of the NumberFormat class−

Modifier and TypeMethod and Description
Objectclone()
Overrides Cloneable.
booleanequals(Object obj)
Overrides equals.
String.format(double number)
Specialization of format.
abstract StringBufferformat(double number, StringBuffer toAppendTo, FieldPosition pos)
Specialization of format.
Stringformat(long number)
Specialization of format.
abstract StringBufferformat(long number, StringBuffer toAppendTo, FieldPosition pos)
Specialization of format.

Example

Let us now see an example to implement the NumberFormat class −

 Live Demo

import java.text.NumberFormat;
import java.util.Locale;
public class Demo {
   public static void main(String[] args) {
      NumberFormat n = NumberFormat.getCurrencyInstance(Locale.FRANCE);
      double points = 2.15;
      double totalPoints = points * 1000;
      System.out.println(n.format(points));
      System.out.println(n.format(totalPoints));
   }
}

Output

This will produce the following output -

2,15 €
2 150,00 €

Example

Let us now see another example −

 Live Demo

import java.text.NumberFormat;
import java.util.Locale;
public class Demo {
   public static void main(String[] args) {
      Locale enLocale = new Locale("en", "US");
      Locale daLocale = new Locale("da", "DK");
      NumberFormat numberFormat = NumberFormat.getInstance(daLocale);
      System.out.println(numberFormat.format(100.76));
      numberFormat = NumberFormat.getInstance(enLocale);
      System.out.println(numberFormat.format(100.76));
   }
}

Output

This will produce the following output -

100,76
100.76

Updated on: 02-Jan-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements