Java Double format via NumberFormat

Introduction

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

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 w w  .java 2 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(76543.404);
      System.out.println(result2);

      // Format a double value for an Italian locale
      result = NumberFormat.getInstance(Locale.ITALIAN).format(65432.404);
      System.out.println(result2);

   }
}



PreviousNext

Related