Java Fundamentals  «Prev 

Floating Point Numbers

Floating-point numbers are numbers with fractional parts, and are represented by the float and double data types.
Similar to the integer data types, the difference between the two floating-point data types is the amount of memory required for storage. The float type requires 32 bits of memory while the double type requires 64 bits.
Although the double type can store much larger (and smaller) numbers than a float, floats are usually sufficient for storing floating-point numbers in most programs.

Floating-Point Types

Java has IEEE 754 single and double precision types supported by keywords:
float f = 0.1f; // 32 bit float, note f suffix
double d = 0.1d; // 64 bit float, suffix optional

The strictfp keyword on classes, interfaces and methods forces all intermediate results of floating-point calculations to be IEEE 754 values as well, guaranteeing identical results on all platforms. Without that keyword, implementations can use an extended exponent range where available, resulting in more precise results and faster execution on many common CPUs.


Floating point number considerations

Floating point numbers are represented internally using the IEEE 754 Floating Point Arithmetic standard. These operations are normally performed in the software, because not all platforms provide hardware support for the standard. Performing these operations in the software will be slower than those executed directly in the hardware. The advantage of performing these operations in the software is that it supports the portability of applications.
Two floating point types are supported, float and double, with their precisions shown in the following table. In addition, the Integer and Float classes are wrapper classes for these two data types. Wrapper classes are used to encapsulate a value, such as an integer or floating point number:

Data type Size (bytes) Precision
float4 23 binary digits
double 8 52 binary digits

Working with floating point numbers can be more complex than working with other data types. There are several aspects of floating point numbers that need to be considered. These include:
  1. Special floating point values
  2. Comparing floating point numbers
  3. Rounding errors