Why java gives wrong answer

float f=40.3f;System.out.println(f%4);The answer for above must be 0.3 but java gives 0.29999924WHY?(This answer is ok for small calculations but it may give wrong answers for large calculations)
[230 byte] By [chamila1986a] at [2007-11-27 4:58:45]
# 1
http://mindprod.com/jgloss/floatingpoint.html
prometheuzza at 2007-7-12 10:14:44 > top of Java-index,Java Essentials,New To Java...
# 2
http://en.wikipedia.org/wiki/Floating_pointSee the part on "Accuracy Problems"
masijade.a at 2007-7-12 10:14:44 > top of Java-index,Java Essentials,New To Java...
# 3
because Java is no Oracle...Java gives the correct answer, but you asked it the wrong question.
jwentinga at 2007-7-12 10:14:44 > top of Java-index,Java Essentials,New To Java...
# 4
> The answer for above must be 0.3Nope.~
yawmarka at 2007-7-12 10:14:44 > top of Java-index,Java Essentials,New To Java...
# 5
This is a well-known problem with Java. Only C# and PL/C are known to give correct answers.Sheesh!Read this: http://docs.sun.com/source/806-3568/ncg_goldberg.html
filestreama at 2007-7-12 10:14:44 > top of Java-index,Java Essentials,New To Java...
# 6

> float f=40.3f;

> System.out.println(f%4);

>

>

> The answer for above must be 0.3 but java gives

> 0.29999924

> WHY?

> (This answer is ok for small calculations but it may

> give wrong answers for large calculations)

Use BigDecimal with MathContext or roll your own Fraction class- this way any repeating decimal is represented exactly.

Message was edited by:

snic.snac

snic.snaca at 2007-7-12 10:14:44 > top of Java-index,Java Essentials,New To Java...