pearmak pearmak - 1 year ago 73
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;


inputnum1 = inputnum.get(0);
inputnum2 = inputnum.get(1);
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);

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 Source

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

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

Output = 0.83 for 0.830000000000041

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download