Paji.R Paji.R - 7 months ago 17
Java Question

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

Answer

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.

Comments