File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "double calculation" Watch "double calculation" New topic

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


[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: 15092

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 8 API documentation
I agree. Here's the link:
subject: double calculation
It's not a secret anymore!