I have two values
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?
Try double instead.
double abc = (double) (5042034.0 + 1425837.2);
Java uses IEEE 754 standard which support 6-7 significant decimal digits. Your addition result cross the range limit so you are getting such result.
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);
To support @xenteros answer, use BigDecimal.
BigDecimal abc = BigDecimal.valueOf(5042034.0 + 1425837.2); System.out.println(abc);
will result in 6467871.2.
Better still, use double which is a primitive:
double abc = (double) (5042034.0 + 1425837.2); System.out.println(abc);
N.B: Just thought to contribute this, I know the OP asked with the help of float.