Android Calculator Truncating unnecessary decimal place after the result
I am getting results always in decimal format like if I enter '1', it gets converted into '1.0' and final result also comes in decimal format. Can anyone tell me how to display user inputs always in simple format instead of decimal format?
This is related to my previous post :
private void handleEquals(int newOperator) {
if (hasChanged) {
switch (operator) {
case 1:
num = num + Double.parseDouble(txtCalc.getText().toString());
break;
case 2:
num = num - Double.parseDouble(txtCalc.getText().toString());
break;
case 3:
num = num * Double.parseDouble(txtCalc.getText().toString());
String strNum = null;
strNum = Double.toString(num);
if(strNum.contains("E")){
strNum = strNum.substring(0, 6) + strNum.substring(strNum.indexOf("E"));
}
Log.i("MULTIPLICATION开发者_StackOverflow社区","Checking Precision");
System.out.println("New StrNum is: " + strNum);
num = Double.valueOf(strNum);
break;
case 4:
num = num / Double.parseDouble(txtCalc.getText().toString());
break;
}
You should test if your number is an integer:
String result;
if (num==(int)num) {
result = String.valueOf((int)num);
} else {
result = String.valueOf(num);
}
// display result to user
Add the following line before break
in every case.
int number = (int)num;
Updated answer:
int num;
num = num + (int)Double.parseDouble(txtCalc.getText().toString());
or
int num;
num = num + Integer.parseInt(txtCalc.getText().toString());
精彩评论