How is floating point stored? When does it matter?
The standard is IEEE 754.
Of course, there are other means to store numbers when IEE754 isn't good enough. Libraries like Java's BigDecimal
are available for most platforms and map well to SQL's number type. Symbols can be used for irrational numbers, and ratios that can't be accurately represented in binary or decimal floating point can be stored as a ratio.
As mentioned, the Wikipedia article on IEEE 754 does a good job of showing how floating point numbers are stored on most systems.
Now, here are some common gotchas:
- The biggest is that you almost never want to compare two floating point numbers for equality (or inequality). You'll want to use greater than/less than comparisons instead.
- The more operations you do on a floating point number, the more significant rounding errors can become.
- Precision is limited by the size of the fraction, so you may not be able to correctly add numbers that are separated by several orders of magnitude. (For example, you won't be able to add 1E-30 to 1E30.)