I want to add two huge floating values but the result I am getting is a little off putting. Let me explain with an example:
String bi = "32323222.02";
float spend=0.00f;
spend = (Float.parseFloat(bi));
String si = "23232322.32";
float spend1=0.00f;
spend1 = (Float.parseFloat(si));
float spendSum=0.00f;
spendSum= spend+spend1;
System.out.println(spendSum);
Now the result for this is 5.5555544E7 whereas I want an answer like 55555544.34. Any suggestions as to what I may be doing wrong with an example will be helpful.
floating point are not exact. This is because there are infinite number of rational numbers in any range, but you only have finite number of bits to represent them.
If you want exact, you should use BigDecimal.
More info on the floating point issue can be found at this [a bit complex] article: What Every Computer Scientist Should Know About Floating-Point Arithmetic
EDIT: Thanks to @ComplicatedSeeBio for his comment, I didn’t notice the result is way off. His answer mentions why the difference is 20% off. However, even without “programming bugs” – you will still not get the result you are expecting due to the floating point issue.