Converting String to Double in Android

178,963

Solution 1

I would do it this way:

try {
  txtProt = (EditText) findViewById(R.id.Protein); // Same
  p = txtProt.getText().toString(); // Same
  protein = Double.parseDouble(p); // Make use of autoboxing.  It's also easier to read.
} catch (NumberFormatException e) {
  // p did not contain a valid double
}

EDIT: "the program force closes immediately without leaving any info in the logcat"

I don't know bout not leaving information in the logcat output, but a force-close generally means there's an uncaught exception - like a NumberFormatException.

Solution 2

try this:

double d= Double.parseDouble(yourString);

Solution 3

You seem to assign Double object into native double value field. Does that really compile?

Double.valueOf() creates a Double object so .doubleValue() should not be necessary.

If you want native double field, you need to define the field as double and then use .doubleValue()

Solution 4

What about using the Double(String) constructor? So,

protein = new Double(p);

Don't know why it would be different, but might be worth a shot.

Solution 5

I had the same issue, but I have just figured out that :

  • parsing the EditText value in the Oncreate method caused the app to crash because when the app starts, there are no values to parse or maybe the placeholders which are letter.

My code:

package com.example.herodav.volumeapp;

import android.renderscript.Double2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    EditText height, length, depth;
    TextView volume;
    double h,l,d,vol;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        height = (EditText)findViewById(R.id.h);
        length = (EditText)findViewById(R.id.l);
        depth = (EditText)findViewById(R.id.d);
        volume = (TextView)findViewById(R.id.v);

        Button btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculateVolume();
                volume.setText("Volume = " + String.valueOf(vol));
            }
        });
    }

    public void calculateVolume(){
        h = Double.parseDouble(height.getText().toString());
        l = Double.parseDouble(length.getText().toString());
        d = Double.parseDouble(depth.getText().toString());
        vol = h*l*d;
    }
}

I

Share:
178,963
Admin
Author by

Admin

Updated on March 22, 2020

Comments

  • Admin
    Admin about 4 years

    Trying to get double values from an EditText and manipulate them before passing them to another Intent. Not using primitive data type so I can use toString methods.

    Problem is when I include the protein=Double.valueOf(p).doubleValue(); style commands, the program force closes immediately without leaving any info in the logcat.If I comment them out and set some dummy data like protein = 1.0; it works with no problems. Same happens with primitive data types and parse double. This code works perfectly with dummy data in normal java. What am I doing wrong?

    EditText txtProt, txtCarb, txtFat, txtFiber, txtPoints;
    String p, c, f, fi;
    Double protein, carbs, fat, fiber;
    double temp;
    Integer points;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         Log.v("Create Prompt", "ready for layout");
         setContentView(R.layout.main);
         Log.v("Layout Created", "ready for variable assignment");
         txtProt = (EditText) findViewById(R.id.Protein);
         txtCarb = (EditText) findViewById(R.id.Carbs);
         txtFat = (EditText) findViewById(R.id.Fat);
         txtFiber = (EditText) findViewById(R.id.Fiber);
         txtPoints = (EditText) findViewById(R.id.Points);
         btnCalc = (Button) findViewById(R.id.Calc);
         Log.v("Variables Assigned", "ready for double assignment");
    
         p = txtProt.getText().toString();
         c = txtCarb.getText().toString();
         f = txtFat.getText().toString();
         fi = txtFiber.getText().toString();
    
    
         protein=Double.valueOf(p).doubleValue();
         carbs=Double.valueOf(c).doubleValue();
         fat=Double.valueOf(f).doubleValue();
         fiber=Double.valueOf(fi).doubleValue();
         Log.v("Doubles parsed", "ready for calculations");
         //these are the problem statements
    
         protein = 1.0;
         carbs = 1.0;
         fat = 1.0;
         fiber = 1.0;
    
         protein *= 16;
         carbs *= 19;
         fat *= 45;
         fiber *= 14;
    
         temp = protein + carbs + fat - fiber;
         temp = temp/175;
    
         points = new Integer((int) temp);
    
  • MikeTheReader
    MikeTheReader almost 13 years
    Also, you're not catching a NumberFormatExeption anywhere in there -- that might be causing your problem. Might want to catch and log that, too, just in case.
  • Admin
    Admin almost 13 years
    why would not catching a NumberFormatException cause the program to force close without even opening?
  • Admin
    Admin almost 13 years
    Yes it does compile. I am using Double instead of double so I can pass the results to another activity through an intent.putExtra(string,string).
  • MikeTheReader
    MikeTheReader almost 13 years
    If you're getting a NumberFormatException somewhere in there, it's going to be tossed up the call stack, into code you don't control. Better to catch it and handle it where you know what it means -- especially when dealing with user input.
  • Admin
    Admin almost 13 years
    protein = new Double(p); didn't work also couldn't get protein=Double.valueOf(p.trim()); to work. also tried protein=Double.parseDouble(p.trim()); no luck
  • Admin
    Admin almost 13 years
    Ah. I understand why I should handle it before I finish the program, I am curious if it would affect the program force closing on launch
  • MikeTheReader
    MikeTheReader almost 13 years
    It might, because whatever in the Android framework is calling your application's create method may not have a clue how to deal with a NumberFormatException.
  • Admin
    Admin almost 13 years
    I've answered my own question there. My xml layout had "" as the default value of the edittext fields. I've put in a 0 to the edittext field and added the try catch blocks.
  • Izkata
    Izkata almost 13 years
    @jkj: It's called autoboxing, and is a documented feature of Java. (EDIT: Rather, auto-unboxing in the case of your comment)
  • Zohab Ali
    Zohab Ali over 5 years
    For kotlin you can use toDouble() like this: val d = textString.toDouble()
  • Joshua Pinter
    Joshua Pinter over 5 years
    How does this compare with Double.valueOf( your String )?
  • waheed shah
    waheed shah over 2 years
    this raises NumberFormatException bcz you are not autoboxing double to Double.