-2

I have the following code in Android Studio.

public void addTotal() {
    String sub1 = subtotal1.getText().toString();
    String newSub1 = sub1.replace("$", "");
    String sub2 = subtotal2.getText().toString();
    String newSub2 = sub2.replace("$", "");
    String sub3 = subtotal3.getText().toString();
    String newSub3 = sub3.replace("$", "");

    totalAmt.setText(newSub1 + newSub2 + newSub3);
}

I have not been able to add them as integer. Am I missing anything?

subtotal1, subtotal2, subtotal3 are TextView in the app.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 3
    yes, you are forgetting to parse them to actual ints. what you are doing is String concatenation, not a mathematical '+' – Stultuske Nov 09 '21 at 06:56
  • I have tried most of the methods i found, but none seems to be able to work for me. App is able to run, until i tried to add and display the total. Guess maybe it's some errors in other parts of my codes. – Chan Jun Mun Nov 10 '21 at 01:24
  • you are unclear of what you get as result, but the description I gave you, and Tim's answer already solve a major issue in your code. Have you tried that? – Stultuske Nov 10 '21 at 06:29

1 Answers1

0

Assuming your text dollar amounts might have a decimal component, you may use Double#parseDouble here:

public void addTotal() {
    String sub1 = subtotal1.getText().replace("$", "");
    String sub2 = subtotal2.getText().replace("$", "");
    String sub3 = subtotal3.getText().replace("$", "");

    Double total = Double.parseDouble(sub1) + Double.parseDouble(sub2) +
                   Double.parseDouble(sub3);
    totalAmt.setText("$" + String.valueOf(total));
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360