Formatting Double and Long Decimal Values - Java Language Basics

Java examples for Language Basics:double

Introduction

Use the DecimalFormat class to format and round the value to the precision.

Demo Code

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

public class Main {

  public static void main(String[] args) {
    formatDouble(new Double("345.9372"));
  }//from  w ww.j a v  a2 s  .com

  public static void formatDouble(double myDouble) {
    NumberFormat numberFormatter = new DecimalFormat("##.000");
    String result = numberFormatter.format(myDouble);

    System.out.println(result);

    // Obtains an instance of NumberFormat class
    NumberFormat format = NumberFormat.getInstance();

    // Format a double value for the current locale
    String result2 = format.format(83.404);
    System.out.println("Current Locale: " + result2);

    // Format a double value for an Italian locale
    result = NumberFormat.getInstance(Locale.ITALIAN).format(83.404);
    System.out.println("Italian Locale: " + result);

    // Parse a String into a Number
    try {
      Number num = format.parse("75");
      System.out.println("Now a number: " + num);
    } catch (java.text.ParseException ex) {
      System.out.println(ex);
    }

  }
}

Result

DecimalFormat Pattern Characters

CharacterDescription
#Digit; blank if no digit is present
0Digit; zero if no digit is present
.Decimal
-Minus or negative sign
,Comma or grouping separator
EScientific notation separator
;Positive and negative subpattern separator

Related Tutorials