0

Hi I am working on an android calculator apps and the now working on the manipuations. I have defined for the following:

ArrayList<Float> inputnum = new ArrayList<Float>(); 
float inputnum1; 
float inputnum2; 

and then for the operations,

case MULTIPLY: 
inputnum1 = inputnum.get(0); 
inputnum2 = inputnum.get(1); 
inputnum.add(inputnum1 * inputnum2);  
Display.setText(String.format("%.9f", inputnum.get(0))); 

similar for the division one.

The muliply function and divide function works well for integers (eg 5* 4 output 20.00000000) however, when it deals with figures with decimal places, eg 5.3 * 4, it output as 21.12000089, which is incorrect.

what is the problem? also, how to set output to Display to remove unnecessary zero? eg when 5*4 it only show 20 instead of 20.000000 as final answer? when 5.3*4 = 21.12 instead of 21.12000000 as final answer?

Thanks a lot!

pearmak
  • 4,979
  • 15
  • 64
  • 122
  • For your first question. Check [this](http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples) – nandeesh Aug 22 '12 at 19:53
  • thanks! it seems that changing all the relevant float to become double then it works, now 1.2 *6.3 = 7.56 instead of 7.560000042. – pearmak Aug 23 '12 at 17:13

1 Answers1

0

Just to change all the related float to double will then avoid presenting the rounding error.

If wanted to present 9 decimal places by filling up zero after the dot, eg 7.56 become 7.560000000, can use the below coding.

Display.setText(String.format("%.9f", inputnum.get(0)));  
pearmak
  • 4,979
  • 15
  • 64
  • 122