Problem with adding Float values ​​in java

I have two meanings

5042034.0 
1425837.2

      

while i add like below

float abc = (float) (5042034.0 + 1425837.2);

      

I expect the result 6467871.2

But I get 6467871.0

How can I get it 6467871.2

using float?

I tried with

 float c = (float) (1.1 + 2.2) ;

      

I got the result: 3.3

What is the reason for this?

+3


source to share


4 answers


Try it double

.



double abc = (double) (5042034.0 + 1425837.2);

      

+3


source


Floats are IEEE 754 32-bit numbers.

5042034.0 is more than 2 ^ 22. This means it fills 23 bits of the mantis, which is the maximum. It actually skips the trailing 0. When you try to add it to 1425837.2, it adjusts both numbers:

 10011001110111101110010.00
+  101011100000110101101.0011001100110011001101....
 --------------------------
 11000101011000100011111.0

      



in the binary system. This means that .0

both .2

do not consist of 22 bits and are skipped.

If you want your arithmetic to be better, use double

or BigDecimal

instead float

:

double result = 5042034.0d + 1425837.2d;
BigDecimal bd = BigDecimal.valueOf(5042034.0d + 1425837.2d);

      

+4


source


To support @xenteros answer use BigDecimal

.

BigDecimal abc = BigDecimal.valueOf(5042034.0 + 1425837.2);
System.out.println(abc);

      

will lead to 6467871.2

.

Better yet, use double

which is primitive:

double abc = (double) (5042034.0 + 1425837.2);
System.out.println(abc);

      

NB: Just thought to contribute, I know the OP asked with float.

+2


source


Java uses the IEEE 754 standard, which supports 6-7 significant decimal digits. Your addition result crosses the range limit, so you get a result like this.enter image description here

+1


source







All Articles