ivesingh
ivesingh

Reputation: 888

How to convert a text into double in Android

I used the following way to change the string into double but unfortunately this closes the app. The EditText inputtype is "NumberDecimal"

numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);

//App forceclose here. Not sure why.
final Double a = Double.parseDouble(numA.getText().toString());
final Double b = Double.parseDouble(numB.getText().toString());

calculate.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
         numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
    }
});

Upvotes: 1

Views: 2199

Answers (3)

Vikram
Vikram

Reputation: 51581

Perform this check:

if (!numA.getText().toString().equals("")) {
    final Double a = Double.parseDouble(numA.getText().toString());
}

if (!numB.getText().toString().equals("")) {
    final Double b = Double.parseDouble(numB.getText().toString());
}

An empty string argument to Double.parseDouble() produces a NumberFormatException.

As a suggestion, if you are working on making a calculator(or converter), you should add more checks for invalid input. For example, you should add a check for when the user inputs just the decimal point(.) or input of form (3.).

Upvotes: 3

Tonithy
Tonithy

Reputation: 2290

You may wish to use a try catch because other unparseable data will throw an exception and it may not be the best to rely on the UI to force valid numbers only.

numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);

Double a;
Double b;
try {
    a = Double.parseDouble(numA.getText().toString());
    b = Double.parseDouble(numB.getText().toString());
} catch (NumberFormatException e) { 
    e.printStackTrace();
    a = 0.0;
    b = 0.0;
}

final double aFin = a;
final double bFin = b;
calculate.setOnClickListener(new View.OnClickListener() {
    //Also, you used your class as an onClickListener you would have to make your doubles final.

    @Override
    public void onClick(View v) {
         numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
         //Division by zero will produce a NaN you should probably check user input data sanity
    }
});

Upvotes: 0

JNL
JNL

Reputation: 4713

Try this;

          String s = b.getText().toString();  
          final double a = Double.valueOf(s.trim()).doubleValue();

Upvotes: 3

Related Questions