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 Type Method and Description
Object clone()
Overrides Cloneable.
boolean equals(Object obj)
Overrides equals.
String. format(double number)
Specialization of format.
abstract StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos)
Specialization of format.
String format(long number)
Specialization of format.
abstract StringBuffer format(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: 2020-01-02T11:05:52+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements