JDK (Java Development Kit) Tutorials
Dr. Herong Yang, Version 5.00

java.util.DecimalFormat.parse() - Parsing Strings to Number Objects

This section provides a tutorial example on how to use the java.util.DecimalFormat.parse() method to parse or convert numeric strings to number objects.

DecimalFormat objects can also be used to parse strings for numbers by using the parse() method. Here is a demonstration program:

import java.util.*;
import java.text.*;
class NumberParsingTest {
   public static void main(String[] a) {
      parseNumbers();
   }
   public static void parseNumbers() {
      DecimalFormat nf = new DecimalFormat("#,##0.00");
      String ns = "-1234.5678";
      Number nv = null;
      DecimalFormat cf = new DecimalFormat("\u00A4#,##0.00");
      String cs = "-$1234.5678";
      Number cv = null;
      DecimalFormat xf 
         = new DecimalFormat("\u00A4#,##0.00;(\u00A4#,##0.00)");
      String xs = "($1234.5678)";
      Number xv = null;
      DecimalFormat pf = new DecimalFormat("#,##0.00%");
      String ps = "-1234.5678%";
      Number pv = null;
      try {
         nv = nf.parse(ns);
         cv = cf.parse(cs);
         xv = xf.parse(xs);
         pv = pf.parse(ps);
      } catch (ParseException e) {
         System.out.println("Exception: " + e.toString());
      }
      System.out.println("Parsing " + ns + " with " + nf.toPattern());
      System.out.println("   " + nv.doubleValue());                    
      System.out.println("Parsing " + cs + " with " + cf.toPattern());
      System.out.println("   " + cv.doubleValue());                    
      System.out.println("Parsing " + xs + " with " + xf.toPattern());
      System.out.println("   " + xv.doubleValue());                    
      System.out.println("Parsing " + ps + " with " + pf.toPattern());
      System.out.println("   " + pv.doubleValue());                    
   }
}

Output:

Parsing -51,234.5678 with #,##0.00
   -51234.5678
Parsing -$51234.5678 with ñ#,##0.00
   -51234.5678
Parsing ($51234.5678) with ñ#,##0.00;(ñ#,##0.00)
   -51234.5678
Parsing -51234.5678% with #,##0.00%
   -512.345678

The result is very interesting:

  • The grouping separator "," is not required in the input string.
  • The numeric digits in the fraction part are not truly respected.

Sections in This Chapter

java.util.NumberFormat - Formatting Numeric Values to Strings

java.util.DecimalFormat.parse() - Parsing Strings to Number Objects

Dr. Herong Yang, updated in 2008
java.util.DecimalFormat.parse() - Parsing Strings to Number Objects