Paji.R
Paji.R

Reputation: 155

Double values not adding together

I have 2 values which I'm trying to add together. Attempting so does not add the decimal place to the value.

int pearInt = (int) Double.parseDouble(pear.getText());
int appleInt = (int) Double.parseDouble(apple.getText());

double result = pearInt + appleInt;

total.setText("" +  result);

pear.getText() & apple.getText() is retrieving from a text field with the values 35.5 and 16.5. When I try add them together, I want it to display 52.0 but it's displaying 51.0

Upvotes: 0

Views: 63

Answers (2)

J. Dow
J. Dow

Reputation: 563

Because you cast your doubles to int. Casting a floating point value to an integer will result in dropping everything behind the dot. Thus you actualy calculate 35 +16

Upvotes: 1

dambros
dambros

Reputation: 4392

The problem is your sum is of 2 ints:

int pearInt = (int) Double.parseDouble(pear.getText());
int appleInt = (int) Double.parseDouble(apple.getText());

This will produces 2 ints, because you are casting the doubles. So simply change to:

double pearInt = Double.parseDouble(pear.getText());
double appleInt = Double.parseDouble(apple.getText());

And you are good to go.

Upvotes: 1

Related Questions