Method to add two values of type float and integer in Android

WEshruth picture WEshruth · Dec 11, 2013 · Viewed 7.8k times · Source

Small Android application, which performs addition and other basic operations, and the OnClick() is as follows

@Override
public void onClick(View v) {
    switch (v.getId()) {
           case R.id.btnAdd: 
           isValidToProcess(1);
           break;
           ......
           /*Switch continues for all other operations like Subtraction,etc*/
    }
}

and my isValidToProcess() is as follows

private boolean isValidToProcess(int a) {
    String num1 = mEdit1.getText().toString();
    String num2 = mEdit2.getText().toString();

    if (num1.matches("") || num2.matches("")) 
    {
        ValueEmptyWarning();
    }
    else {
        float numa = Float.parseFloat(num1);
        float numb = Float.parseFloat(num2);
        switch (a) {

        case 1:
            addition(numa, numb);
            break;
              ......
           /*Switch continues for all other operations like Subtraction,etc*/
    }
}

My addition() function

public void addition(float numa, float numb) {
    answer = numa + numb;
    mEdit3.setText(String.valueOf(answer));
    Log.v(TAG, "Error at Subtraction");
}

This program is working fine for Float and Integer numbers, But the problem is, for both Integer and Float values the answer will be in fractions, For example Number1=2 and Number2=3 and the answer=5.0

Objective: If User inputs Integer, The decimal point should not be there.

Is this possible to get the type of Value which user has entered on EditText?

Answer

nitesh goel picture nitesh goel · Dec 11, 2013

first check for Integer.parseInt(numer) and catch for NumberFormatException . if it will parse it correctly then it is an integer else you can go for float.