Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision.
A number that contains a fractional part is known as a real number, for example, 3.2, 0.1149, -1.19, etc.
Java supports the floating-point number format. Java uses the IEEE 754 Floating-Point standard to store real numbers.
There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively.
Their width and ranges are shown here:
|Name||Width in Bits||Approximate Range|
|double||64||4.9e-324 to 1.8e+308|
|float||32||1.4e-045 to 3.4e+038|
The float data type uses 32 bits to store a floating-point number.
A floating-point number is also known as a single-precision floating-point number. It can represent a real number as small as 1.4 x 10-45 and as big as 3.4 x 1038 in magnitude.
The range includes only the magnitude. It could be positive or negative.
All real numbers that end with f or F are called float literals. A float literal can be expressed in the following two formats:
Examples of float literals in decimal number format are as follows:
float f1 = 1F; float f2 = 2.F; float f3 = 3.0F; float f4 = 4.51F; float f5 = 5.0F; float f6 = 56.78f;
In Java, real numbers can be represented as float literals using scientific notation.
In scientific notation, the number 32.5 x 10-1 is written as 32.5E-1. As a float literal, it can be written as 32.5E-1F or 32.5E-1f.
All of the following float literals denote the same real number 42.5:
4.25F 42.5E-1F 0.425E+1F 0.425E1F 0.0425E2F 0.0425e2F 4.25E0F
The float data type defines two zeros: +0.0F (or 0.0F) and -0.0F. Both +0.0F and -0.0F are considered equal.
The float data type defines two infinities: positive infinity and negative infinity.
Results of some of the operations on float are not defined. For example, dividing 0.0F by 0.0F is indeterminate.
Indeterminate results are represented by a special value of the float data type called NaN (Not-a-Number).
Java has a
Float class, which defines three constants that represent positive infinity,
negative infinity, and NaN of the float data type.
The following table lists these three float constants and their meanings.
|Float.POSITIVE_INFINITY||Positive infinity of type float|
|Float.NEGATIVE_INFINITY||Negative infinity of type float|
|Float.NaN||Not a Number of type float|
|Float.MAX_VALUE||The largest positive value that can be represented in a float variable. This is equal to 3.4 x 1038 (approx.).|
|Float.MIN_VALUE||The smallest positive value greater than zero that can be represented in a float variable. This is equal to 1.4 x 10-45.|
The value of all integral types (int, long, byte, short, and char) can be assigned to a variable of the float data type without using an explicit cast.
A float value must be cast before it is assigned to a variable of any integral data type int, long, byte, short, or char.
The assignment of int and long to float may result in loss of precision.