Formatting Numbers Using Default Formats - Java Language Basics

Java examples for Language Basics:Number Format

Description

Formatting Numbers Using Default Formats

Demo Code

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

public class Main {
  public static void main(String[] args){
    double value = 1234567.895 ;
    /*from   www  .jav a 2  s. c o  m*/
    // Default locale
    printFormatted(Locale.getDefault(), value);

    // Indian locale
    Locale indianLocale = new Locale("en", "IN");
    printFormatted(indianLocale, value);
  }
  
  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));
    System.out.println();
  }
}

Result


Related Tutorials