Float operation

Hello,

I'm sorry about asking this question again, but I have not found any response clear enough!

The addition of float primitives do not return an exact value. For example :

float f1 = 4.8f;

float f2 = 0.8f;

System.out.println(f1+f2);

System.out.println(new BigDecimal(f1).add(new BigDecimal(f2)).floatValue());

Result :

5.6000004

5.6000004

There is an excellent raison for that, and I don't care about it.

The true is that this result is false, 4.8 + 0.8 = 5.6

What is the simplest way for doing that?

My apologies for my english.

[762 byte] By [Keega] at [2007-11-27 8:54:11]
# 1

import java.math.*;

public class BigExample {

public static void main(String[] args) {

BigDecimal f1 = new BigDecimal("4.8");

BigDecimal f2 = new BigDecimal("0.8");

BigDecimal sum = f1.add(f2);

System.out.println(sum);

BigDecimal sum2 = new BigDecimal("5.6");

System.out.println(sum.equals(sum2));

}

}

BigDaddyLoveHandlesa at 2007-7-12 21:13:11 > top of Java-index,Java Essentials,Java Programming...
# 2

3 ways to get your exact value.

float f1 = 4.8f;

float f2 = 0.8f;

System.out.printf("%.1f%n",f1+f2);

System.out.println(((f1*10)+(f2*10))/10);

System.out.println(new BigDecimal("4.8").add(new BigDecimal("0.8")).floatValue());

~Tim

SomeoneElsea at 2007-7-12 21:13:11 > top of Java-index,Java Essentials,Java Programming...
# 3
> There is an excellent raison for that, and I don't> care about it. But if you are on this business you should care about it. Take a look http://docs.sun.com/source/806-3568/ncg_goldberg.htmlManuel Leiria
manuel.leiriaa at 2007-7-12 21:13:11 > top of Java-index,Java Essentials,Java Programming...