Java floating-point numbers represent decimal values with a fractional part.
They can be expressed in either standard or scientific notation.
Standard notation has a whole number component followed by a decimal point followed by a fractional part.
For example, 2.0
, 3.14159
, and 0.1234
are all valid standard-notation floating-point numbers.
Scientific notation uses a floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied.
The exponent is indicated by an E
or e
followed by a decimal number, which can be positive or negative.
For examples, 6.012E23, 314159E-05, and 2e+100.
Floating-point literals in Java default to double precision.
To specify a float literal, you must append an F
or f
.
You can explicitly specify a double literal by appending a D
or d
.
Hexadecimal floating-point literals are supported.
They must be in a form similar to scientific notation, but a P
or p
, rather than an E
or e
.
For example, 0x12.2P2 is a valid floating-point literal.
The value following the P, called the binary exponent.
It indicates the power-of-two by which the number is multiplied.
Therefore, 0x12.2P2 represents 72.5.
We can embed one or more underscores in a floating-point literal.
For example, given
double num = 9_876_543_210.0;
The underscores can only be used to separate digits.
They cannot come at the beginning or the end of a literal.
We can use more than one underscore between two digits.
We can also use underscores in the fractional portion of the number.
For example,
double num = 9_423_497.1_0_9;