Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with adding Float values In java

I have two values

5042034.0 
1425837.2

while I am adding like below

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

I am expecting a result of 6467871.2

But I am getting 6467871.0

How could I get the 6467871.2 with the help of float?

I tried with

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

I got a result : 3.3

What is the reason behind this?

like image 611
ShaiNe Ram Avatar asked Sep 13 '25 07:09

ShaiNe Ram


2 Answers

Floats are IEEE 754 32-bit numbers.

5042034.0 is over 2^22. This means, that it fills 23 bits of mantisa which is the maximum. It actually skips the trailing 0. When you're trying to add it to 1425837.2 it adjusts both numbers:

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

in binary system. It means that .0 and .2 are out of 22 bit and are skipped.

If you want your arithmetic to be better, use double or BigDecimal instead of float:

double result = 5042034.0d + 1425837.2d;
BigDecimal bd = BigDecimal.valueOf(5042034.0d + 1425837.2d);
like image 156
xenteros Avatar answered Sep 15 '25 20:09

xenteros


Try double instead.

double abc = (double) (5042034.0 + 1425837.2);
like image 24
gprathour Avatar answered Sep 15 '25 21:09

gprathour