Error converting String to Double

3

Scenery:

public void metodoX(Double valor) {

    DecimalFormat df = new DecimalFormat("0.00");
    String valorRound = df.format(valor);
    Double valorRound2 = Double.parseDouble(valorRound);
    ...
}

Error:

Caused by: java.lang.NumberFormatException: Invalid double: "3,67"

Error line:

Double valorRound2 = Double.parseDouble(valorRound);

Details:

The app is rodando perfeitamente no emulador API 23 , but running in celular API 23, causa esse erro .

Why only the phone gives the error?

I've tried:

Double valorRound2 = Double.valueOf(valorRound);
    
asked by anonymous 18.12.2017 / 16:56

2 answers

2
  

Why only the phone gives the error?

It gives one error and not the other because the decimal separator depends on the Locale defined on the device. In some it is . , in others it is , .

I suppose this value is entered by the user, so you have to ensure that it is entered in the correct format.

One of the possible ways to do this is to indicate android:inputType="numberDecimal" in the EditText declaration:

<EditText
   android:id="@+id/edittext"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="0" 
   android:inputType="numberDecimal"/>

Editing after comment:

  

It is not in the input no, it is a SeekBar with variation 0.01 (...)

In this case do so:

DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);

String valorRound = df.format(valor);
Double valorRound2 = Double.parseDouble(valorRound);
    
18.12.2017 / 17:48
2

Explanation

You're having an exception for some reason, so in a situation where there might be exceptions, you should treat exceptions with try/catch .

Codes

Resulting in this way:

public void metodoX(Double valor) {

  try {
    DecimalFormat df = new DecimalFormat("0.00");
    String valorRound = df.format(new Double(valor));
    Double valorRound2 = Double.parseDouble(valorRound);
  } catch (NumberFormatException e) {
    valor = 0; //valor padrão
  }
  ...
}

However, the problem in question seems to be with Locale and its differences in Doubles handling between , and . , so I'd recommend using DecimalFormatSymbols to avoid comma issues, like this:

Locale meuLocale = new Locale("pt", "BR");
DecimalFormatSymbols simbolos = new DecimalFormatSymbols(meuLocale);
simbolos.setDecimalSeparator(',');
simbolos.setGroupingSeparator('.'); 
DecimalFormat df = new DecimalFormat(valor, simbolos);
  

(According to the comment from @Jefferson Quesado, probably the locale is the cause of the divergence of operation, so applying this last block of code would solve.)

    
18.12.2017 / 17:15