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?
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);
Try double
instead.
double abc = (double) (5042034.0 + 1425837.2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With