Java Reference
In-Depth Information
To represent real numbers, Java uses a form of scientific notation called floating-point
notation. Table 2-3 shows how Java might print a set of real numbers. In the Java
floating-point notation, the letter e stands for the exponent.
2
TABLE 2-3
Examples of Real Numbers Printed in Java Floating-Point Notation
Real Number
Java Floating-Point Notation
75.924
7.592400e+01
0.18
1.800000e-01
0.0000453
4.530000e-05
-1.482
-1.482000e+00
7800.0
7.800000e+03
Java provides two data types to represent decimal numbers:
float
and
double
. As in the
case of integral data types, the data types
float
and
double
differ in the set of values.
float
:
The data type
float
is used in Java to represent any real number between
3.4E+38 and 3.4E+38. The memory allocated for the
float
data type is 4 bytes.
double
:
The data type
double
is used in Java to represent any real number between
1.7E+308 and 1.7E+308. The memory allocated for the
double
data type is 8 bytes.
Other than the set of values, there is one more difference between the data types
float
and
double
. The maximum number of significant digits—that is, the number of decimal
places—in
float
values is 6 or 7. The maximum number of significant digits in values
belonging to the
double
type is typically 15. The maximum number of significant digits
is called the precision. Sometimes
float
values are called single precision, and values
of type
double
are called double precision.
In Java, by default, floating-point numbers are considered to be of type
double
.
Therefore, if you use the data type
float
to represent floating-point numbers in a
program, you might get a warning or an error message, such as ''truncation from
double to float'' or ''possible loss of data.'' To avoid such messages, you should use
the
double
data type. For illustration purposes and to avoid such messages in
programming examples, this topic mostly uses the data type
double
to represent
floating-point numbers. However, if you need to explicitly use a
float
value in a
program, specify that the decimal value is a
float
value using the letter f at the
end of the number. For example, 28.75f represents a
float
value while 28.75
represents a
double
value.
Search WWH ::
Custom Search