Beware of floating point numbers

Outside of a scientific or engineering context, the use of float and double (and the corresponding wrapper classes Float and Double) should likely be avoided. The fundamental problem is that rounding errors will always occur when using these data types - they are unavoidable.

In a typical business application, using float and double to represent money values is dangerous, because of these rounding issues. Instead, BigDecimal should usually be used to represent money.

From an IBM article on this topic:

"...binary floating-point arithmetic should not be used for financial, commercial, and user-centric applications or web services because the decimal data used in these applications cannot be represented exactly using binary floating-point."

From an article by Brian Goetz:

" is a bad idea to use floating point to try to represent exact quantities like monetary amounts. Using floating point for dollars-and-cents calculations is a recipe for disaster. Floating point numbers are best reserved for values such as measurements, whose values are fundamentally inexact to begin with."

See Also :
Representing money
Avoid basic style errors
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -