This is the 33rd Step towards gaining the Programming Enlightenment series. If you didn’t learn the 32nd Step, read it.
“95% of folks out there are completely clueless about floating-point.” ~ James Gosling
The term floating point is derived from the fact that there is no fixed number of digits before and after the decimal point; that is, the decimal point can float.
In Java, The float
data type or Floating-point Number is a single-precision 32-bit IEEE 754 floating point.
What is the problem with Floating-Point Number?
To illustrate, assign 2147483647 (the largest signed 32-bit integer) to a 32-bit float variable (x, say), and print it. You’ll see 2147483648. Now print x - 64
. Still 2147483648. Now print x - 65
and you'll get 2147483520! Why? Because the spacing between adjacent floats in that range is 128, and floating-point operations round to the nearest floating-point number.
IEEE floating-point numbers are fixed-precision numbers based on base-two scientific notation: 1.d1d2…dp-1 × 2e, where p is the precision (24 for float, 53 for double). The spacing between two consecutive numbers is 21-p+e, which can be safely approximated by ε|x|, where ε is the machine epsilon (21-p).
Also, if you execute the following you will be astonished
double x1 = 0.3;
double x2 = 0.1 + 0.1 + 0.1;
System.out.println(x1 == x2); // Prints false
double z1 = 0.5;
double z2 = 0.1 + 0.1 + 0.1 + 0.1 + 0.1;
System.out.println(z1 == z2); // Prints True
TL;DR Don’t use Floating point number for financial applications. Remember the rounding errors and code accordingly.
Go to 32nd Step
Go to the 34th Step.
References:
- 97 things Every Programmer Should Know ~ Git Book
- 97 Things Every Programmer Should Know ~ Paperback
- Floating-Point Types ~ Oracle
- What is floating point? ~ Princeton
- Primitive Data Types in Java ~ Oracle
- What every Computer Scientist Should Know About Floating-Point Arithmetic ~ Oracle
- Double ~ Princeton