javajformattedtextfield

How to convert a "formatted double(String)" to double?


I have the following code :

 NumberFormat nf=NumberFormat.getInstance(Locale.FRANCE);
   nf.setMinimumFractionDigits(3);
    String  s=  nf.format(3456.32);
//   double d= Double.valueOf(s); error here
    System.out.println(s);

This code displays :

3 456,320

it's good until now, but imagine when I get the same format from a JFormattedTextField, how I can transform a "3 456,320" as a String to double(3456.32) ?

I have already tried this :

String s="3 456,320";
double d= Double.valueOf(s);

but i get an error...

EDIT:

after several tests, I found the code is not so robust ,for example :

 //this works
 String s="3456,6567";

 NumberFormat nf1=NumberFormat.getInstance(Locale.FRANCE);

 double d = (double) nf1.parse(s);

but this one:

 String s="3456,0";

 NumberFormat nf1=NumberFormat.getInstance(Locale.FRANCE);

 double d = (double) nf1.parse(s);

I get this error :

Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double

by cons I find this very robust:

    double d = nf1.parse(s).doubleValue();

we must test the software several times !!!


Solution

  • Try using NumberFormat again.

    NumberFormat nf=NumberFormat.getInstance(Locale.FRANCE);
    String s = "3 456,320";
    double d = nf.parse(s);