*
The moose likes Java in General and the fly likes double calculation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "double calculation" Watch "double calculation" New topic
Author

double calculation

Ronnie Ho
Ranch Hand

Joined: Aug 10, 2005
Posts: 47
Hi all,

Why does

gives 0.5800000000000001 ? where does the .0000...001 come from ? Thanks.
[ October 17, 2005: Message edited by: Ronnie Ho ]
Grant Gainey
Ranch Hand

Joined: Oct 16, 2005
Posts: 65
The short answer is, computers store their data in binary, and "5.8" is not precisely representable.

The slightly-longer answer is that Java uses IEEE-754 to store/represent floating-point numbers, and the number you're seeing is the closest one can come to 5.8 in that format.

The best answer is that it's important to understand that a programming language's "float" and "double" are not the same as the real number line. Check out this link for a great explanation:

What Every Computer Scientist Should Know About Floating Point

Grant

[Edited to fix broken tags]
[ October 19, 2005: Message edited by: G Gainey ]

In Theory, there is no difference between theory and practice.<br />In Practice, there is no relationship between theory and practice.
Ronnie Ho
Ranch Hand

Joined: Aug 10, 2005
Posts: 47
Thanks. I'll just take the short answer. The link contains too much details.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I always jump in when I see two decimal points. If you're dealing with money, floating types will probably make you very unhappy. You've already started to see why. The PowerBall is at $340 million so I'm thinking about money again today.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

So if you're dealing with amounts of money in your application, use java.math.BigDecimal instead of float or double.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: double calculation
 
Similar Threads
confusion in output
does == count as arithmetic calculation?
Positive Infinity
addition accuracy
yet another postfix/prefix precedence question