Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Tried with float and double - same result. Please help.
Posted

It's a fact of life with floats and doubles etc. (decimals are better).

Read this for the why : http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html[^]
 
Share this answer
 
Comments
Member 10545052 29-Jan-14 3:05am    
Not helped - same problem :(
CPallini 29-Jan-14 3:07am    
5.
Mehdi Gholam 29-Jan-14 3:09am    
Cheers!
Member 10545052 29-Jan-14 3:13am    
Clear. It works correctly only with strings:
new BigDecimal(operand_a + "") instead
new BigDecimal(operand_a)
Hello.
An issue is Java uses IEEE 754[^] standard. Consider not to use float, use double instead. When one uses floating point numbers he should be careful.
For further details please see What Every Computer Scientist Should Know About Floating-Point Arithmetic[^]
As for your question... You should use some round operations or to manipulate values with help of BigDecimal[^] or something like that.
Java
BigDecimal a = new BigDecimal("2.3");
BigDecimal b = new BigDecimal("1.2");
BigDecimal c = a.subtract(b);

Please follow this link[^] for other cases.
Good luck.
 
Share this answer
 
Comments
Member 10545052 29-Jan-14 3:05am    
Not helped - same problem :(
CPallini 29-Jan-14 3:07am    
5.
Member 10545052 29-Jan-14 3:12am    
Clear. It works correctly only with strings:
new BigDecimal(operand_a + "") instead
new BigDecimal(operand_a)
skydger 29-Jan-14 3:32am    
Well, it works with doubles too if to use MathContext in constructor:
MathContext mc = new MathContext(2, RoundingMode.HALF_UP)
BigDecimal a = new BigDecimal(2.3d, mc);

http://docs.oracle.com/javase/1.5.0/docs/api/java/math/MathContext.html
skydger 29-Jan-14 3:27am    
Thank you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900