permaculture playing cards*
The moose likes Java in General and the fly likes How to add two double values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to add two double values" Watch "How to add two double values" New topic
Author

How to add two double values

sowmya vasisht
Ranch Hand

Joined: Aug 23, 2001
Posts: 35
I am facing one problem in adding two double values. When I add 12.12 + 0.01, it is giving 12.129999999999999.

Can any one please help me out in this.

Thanks in Advance
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8843
    
    7

Floating-point numbers on a computer, like java's double and float primitive types, are approximate values. There has to be a compromise between the precision of a value and the amount of memory it would take to represent it. Otherwise how could we represent a number like pi, which has an infinite number of digits? This article is a good introduction to the concepts and pitfalls of floating-point numbers. Incidentally, java provides two classes in the java.math classes for representing arbitrary-precision values, like when working with money.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
Also, you might want to read up on the strictfp keyword that was added around the JDK 1.3 (I think). I'm not sure this will solve your problem...I'm pretty sure use of that keyword only guarantees that all calculations will result in the same value regardless of the platform your classes happen to be running on.

There's been a lot of time and energy devoted to doing exact calculations in computing. All you have to do is look and you'll find a lot...I think even Knuth's canon of numerical algorithms addresses this topic.

Or you can grow your own. Java provides the java.math.BigDecimal class which you might find useful.

sev
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to add two double values
 
Similar Threads
Trouble with model for calculating and adding table values dependent on multiple rows
Top Secret...
What data structure?
Third Overloaded method not compiling
Retrieving different keys when the values in a hashmap are same???