• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to add two double values

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Bartender
Posts: 9626
16
Mac OS X Linux Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 (the document this link points to has been removed by IBM. The Internet Archive has an archived copy. Keep in mind that this information is many years old and may not reflect the current state of art) 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.
 
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic