Both float and double data types represent floating point numbers in Java. The float data type is a single-precision 32-bit IEEE 754 floating point number and the double data type is a double-precision 64-bit IEEE 754 floating point.
IEEE Standard for Floating-Point Arithmetic (IEEE 754)
The float data type contains 1 sign bit, 8 bits of exponent, and 23 bits of the mantissa (totally 32 bits) and the double data type contains 1 sign bit, 11 bits of exponent, and 52 bits of mantissa (totally 64 bits).
Every floating point number has the following representation in IEEE 754.
If the sign bit is 0, then the number is a positive number. If the bit is 1, then the number is negative.
To find exponent part in the formula, calculate the exponent of floating point number and subtract 127.
Mantissa value of floating point number contains 23 bits (see the figure below). First bit represents 0.5 (1/2), second bit represents 0.25 (1/4), third bit represents 0.125 (1/8) , ….
To find the mantissa part in the formula, calculate the mantissa of floating point number and add 1.
Following figure shows representation of a floating number in IEEE 754 standards.
The floating number in the figure above is 2.25. Let’s analyze step by step how this value is found.
Leftmost bit is 0, so the number is a positive number.
Exponent of floating point number is 1 0 0 0 0 0 0 0, which is 128 in decimal. 128 – 127 gives the exponent part in the formula.
Mantissa of floating point number is 0 0 1 0 0 0 0 . . . . . = 0.125. To find mantissa part in the formula add 1 (1.125).
When to Use Float and When to Use Double?
Both float and double cannot represent all real numbers precisely, but if you need more precision you can use double instead of double. Since double is 64 bit floating point number, it can hold more precise values. Float can handle 6-7 decimal points, double can handle 15-16 decimal points.
Double type is also handy for dealing with bigger numbers, because its range is wider. Float has range from 1.4e-45 to 3.4e+38, double has range from 1.7e-308 to 1.7e+308.
Usually, it’s OK to use double type for floating points, but you can use float type for performance optimization. Float holds less memory than double. Float type is mainly used in game programming, because double precision is not required in most of the games and GPUs are optimized for floats.
Usage of Float and Double Types
- In Java, double is the default type used to represent floating point numbers. If you want to create a floating point number and assign it to float data type you need to cast it explicitly as shown below:
float pi = (float)3.14;orfloat pi = 3.14f;
- You shouldn’t compare floats or doubles with == opeartor. Becase double and float aren’t precise data types, you might get unexpected results.
- If you need complete precision, you should use BigDecimal instead of double or float.