Java - Data Format Formatting Numbers

Introduction

The following two classes can be used to format and parse numbers:

java.text.NumberFormat
java.text.DecimalFormat

NumberFormat class formats a number in a particular locale's predefined format.

DecimalFormat class formats a number in a custom format in a particular locale.

You can use a getXXXInstance() method of the NumberFormat class to create the instance of a formatter object, where Xxx can be replaced by Number, Currency, Integer, or Percent, or just getInstance().

The following code shows how to create NumberFormat object.

NumberFormat formatter;
// Get number formatter for default locale
formatter = NumberFormat.getNumberInstance();

// Get number formatter for French locale
formatter = NumberFormat.getNumberInstance(Locale.FRENCH);

// Get currency formatter for German
formatter = NumberFormat.getCurrencyInstance(Locale.GERMAN);

The following code illustrates how to format numbers in default format for three locales.

  • United States is the default locale
  • French locale, and
  • German locale.

Demo

import java.text.NumberFormat;
import java.util.Locale;

public class Main {
  public static void main(String[] args) {
    double value = 12345678.785;

    // Default locale
    printFormatted(Locale.getDefault(), value);

    // Indian locale, (Rupee is the Indian currency. Short form is Rs.)
    Locale indianLocale = new Locale("en", "IN");
    printFormatted(indianLocale, value);
  }//from   w w w  .ja v a  2  s .  c o m

  public static void printFormatted(Locale locale, double value) {
    // Get number and currency formatter
    NumberFormat nf = NumberFormat.getInstance(locale);
    NumberFormat cf = NumberFormat.getCurrencyInstance(locale);

    System.out.println("Formatting value: " + value + " for locale: " + locale);
    System.out.println("Number: " + nf.format(value));
    System.out.println("Currency: " + cf.format(value));
  }
}

Result

Related Topics