pearmak pearmak - 3 months ago 9
Android Question

Android Calculator subtraction

I am working on an android calculator. the user is pressing the buttons for 1 to 9 and decimal dot, and then inputnum (arraylist ) would then parse the display as input, and then oepration and then display the answer. The related codes as follows:

ArrayList<Double> inputnum = new ArrayList<Double>();
double inputnum1;
double inputnum2;

...


inputnum.add(Double.parseDouble(Fakedisplay.getText().toString()));
case SUBTRACT:
inputnum1 = inputnum.get(0);
inputnum2 = inputnum.get(1);
inputnum.removeAll(inputnum);
inputnum.add(inputnum1 - inputnum2);

Fakedisplay.setText(String.format("%.19f", inputnum.get(0)));

String strf2=Fakedisplay.getText().toString();
String strippedf2 = Double.valueOf(strf2).toString();
if (strippedf2.endsWith(".0"))
strippedf2 = strippedf2.substring(0, strippedf2.length() - 2);
Fakedisplay.setText(strippedf2);


Problem:
For 1000.84 - 1000.01 it will gives 0.830000000000041, which is not desired for the presentation,
Yet this problem just only occur for subtraction, exactly the same codings for add, multiply and division but work very well, ie: 1000.84+ 1000.01 presenting 2000.85 and no more, 1000.84*1000.01=1000850.0084 and no more, 1000.84/1000.01 also works and present correctly.

Why is it so special for subtraction? how to handle it?

Answer

Try Decimal Format to Show long value upto N Decimal Digit.

DecimalFormat round = new DecimalFormat ("###.##");
String output = round.format(inputnum.get(0));
Fakedisplay.setText(output); 

Output = 0.83 for 0.830000000000041

Comments