NumberFormatException String to Double to String

0

I have a question related to the JVM of java.

We have a double in the form of String and we want to parse it to double , so we wanted to check if the ',' parsea to '.' correctly. If you execute this piece of code:

System.out.println(String.valueOf(Double.parseDouble("98,71")));

The exception will skip:

  

java.lang.NumberFormatException: For input string: "98.71"

On the other hand, if you try to parse it in this way, no exception will be thrown:

double x = Double.parseDouble("23,34");

String result = String.valueOf(x);

System.out.println(result);

Let's say that the purpose of all this is to pair double a number in String format that is written with ',' and the number , when collecting the double , the ',' will be parsed by '.' and later I will pause again the double to a String and the number will have a '.' instead of a ',' .

It is clear that there are many ways to do this, but my goal with this question is to know why in the first System.out.println that I have given you% error NumberFormatException .

Deputy proof that you parse correctly in option 2.

    
asked by DazzelWazzel 24.08.2018 в 10:38
source

1 answer

2

The parseDouble function of format expects the text with the Locale that you have defined. It is possible that in one example you had it with Locale in English and in the other in Spanish. If you put this code

 try {
            NumberFormat format = NumberFormat.getInstance(Locale.FRANCE); // usa . como el español.
            Number numero = format.parse("23,24");
            System.out.println("Numero frances: "+ numero.doubleValue());
        } catch (ParseException k)
        {
            System.out.println("Errro al cmabiar numero con Locale Frances");
        }
        try {
            // Asi no funciona
            NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
            Number numero = format.parse("23,24");
            System.out.println("Numero ingles: "+ numero.doubleValue());
        } catch (ParseException k)
        {
            System.out.println("Errro al cmabiar numero con Locale Ingles");
        }

You will see that the output is the following:

Numero frances: 23.24
Numero ingles: 2324.0

The fact is that the Double class always uses the English locale, and in your example it gives an error in both cases.

    
answered by 24.08.2018 в 11:54