0

This is a simple add operation between two float:

float a = 3.9F;
float b = 2.95F;
Log.i("Operation","sum: "+String.valueOf(a+b));

This return me the following output:

11-26 15:02:15.680: I/Operation(18403): sum: 6.8500004

How can I obtain the correct value(6.85) ?

GVillani82
  • 17,196
  • 30
  • 105
  • 172
  • Take a look at http://stackoverflow.com/questions/1661273/floating-point-arithmetic-not-producing-exact-results-in-java. – tjg184 Nov 26 '13 at 14:07
  • 1
    Also take a look at [DecimalFormat](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) provided in `java` api. – Andrew Schuster Nov 26 '13 at 14:08
  • 1
    There's always an estimation while using Float, same thing with Double. You shall approximate to a number of decimal. Try BigDecimal instead if you need result, DecimalFormat like andrew Schuster says if you only need printing – Baptiste Gousset Nov 26 '13 at 14:09

3 Answers3

3

You should use the DecimalFormat class.

Example

DecimalFormat decFormat = new DecimalFormat("#.##");
Log.i("Operation", "sum: " + decFormat.format(a + b));

If you want to ensure that there are always going to be two decimal places, i.e: 2.90 or 2.00, then you can do something like:

DecimalFormat decFormat = new DecimalFormat("0.00");
Log.i("Operation", "sum: " + decFormat.format(a + b));
christopher
  • 26,815
  • 5
  • 55
  • 89
0

try this...

DecimalFormat format = new DecimalFormat("###.##");
String val = format.format(1.2223F+1.4334F);
System.out.println(val);
Nunser
  • 4,512
  • 8
  • 25
  • 37
subash
  • 3,116
  • 3
  • 18
  • 22
0

You can use format method of System.out, so that you can decide the specific output format:

float a = 3.9F;
float b = 2.95F;
System.out.format("%.2f", a + b);

Output will be:

6.85

In here, as you can guess, %f takes float type of argument and .2 between % and f characters means you want output of this float argument with 2 decimal numbers.