Btxbills
Btxbills

Reputation: 23

Invalid Double " " on String to Double to String conversion

I am converting a textView to Double then performing calculations then converting back to a string. I see that when my textview = "" it is throwing the error invalid Double "".

I added a check on the length of the text view prior to the calculation but it still is throwing the error. Any help is appreciated.

    public void afterTextChanged(Editable s) {
        if (textView.toString().length() > 0) {
            Double ini = Double.parseDouble(textView.getText().toString());
            Double calc = ini * 3.2808;
            //passwordEditText.setText(textView.getText());
            passwordEditText.setText(Double.toString(calc));
        } else {
        passwordEditText.setText("");
        }
    }

Upvotes: 1

Views: 148

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109547

String text = textView.getText().trim();
if (!text.isEmpty()) {
    try {
        double ini = Double.parseDouble(text);
        double calc = ini * 3.2808;
    } catch (NumberFormatException e) {
        ---

double being the primitive type, Double an object wrapper, a bit more circumstantial converting ("unboxing") to double.

However parseDouble uses the computer language format: with a decimal point and no thousands separators. For another locale like most European countries the decimal separator is a comma. For portability:

NumberFormat nf = NumberFormat.getInstance(); // Default
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); // Or fixed

try {
    Number n = nf.parse(text);
    double ini = n.doubleValue();
    ...
} catch (ParseException e) {
    ...

Even if parseDouble would suffice in your case, now thousand separators are possible. And for displaying numbers, a NumberFormat is even more useful.

Upvotes: 0

Joni
Joni

Reputation: 111219

Use the getText method to get the text from a TextView. The toString method returns something else - a textual representation of the view itself. You can also trim it, in case there is extra whitespace.

    String text = textView.getText().toString().trim();
    if (text.length() > 0) {
        Double ini = Double.parseDouble(text);

Upvotes: 2

Darshan Mehta
Darshan Mehta

Reputation: 30809

May be you are getting an empty string as a value, try changing if condition to the following:

if (textView.toString().trim().length() > 0) {
    //logic
}

Upvotes: 0

Related Questions