Java Reference
In-Depth Information
Floating Point Data Types
Numeric values that are not integral are stored as floating point numbers. A floating point number has a
fixed number of digits of accuracy but with a very wide range of values. You get a wide range of values,
even though the number of digits is fixed, because the decimal point can "float". For example the values
0.000005, 500.0, and 5000000000000.0 can be written as 5x10 -6 , 5x10 2 , and 5x10 12 respectively - we
have just one digit '5' but we move the decimal point around.
There are two basic floating point types in Java, float and double . These give you a choice in the
number of digits precision available to represent your data values, and in the range of values that can be
accommodated:
Data Type
Description
float
Variables of this type can have values from -3.4E38 (-3.4x10 38 ) to +3.4E38
(+3.4x10 38 ) and occupy 4 bytes in memory. Values are represented with
approximately 7 digits accuracy.
Variables of this type can have values from -1.7E308 (-1.7x10 308 ) to +1.7E308
(+1.7x10 308 ) and occupy 8 bytes in memory. Values are represented with
approximately 17 digits accuracy. The smallest non-zero value that you can have
is roughly
double
±
4.9x10 -324 .
All floating point operations and the definitions for values of type float and type
double in Java conform to the IEEE 754 standard.
As with integer calculations, floating point calculations in Java will produce the same results on
any computer.
Floating Point Values
When you are specifying floating point literals they are of type double by default, so 1.0 and 345.678
are both of type double . When you want to specify a value of type float , you just append an f , or an
F , to the value, so 1.0f and 345.678F are both constants of type float . If you are new to
programming it is important to note that you must not include commas as separators when specifying
numerical values in your program code. Where you might normally write a value as 99,786.5, in your
code you must write it without the comma, as 99786.5.
When you need to write very large or very small floating point values, you will usually want to write
them with an exponent - that is, as a decimal value multiplied by a power of 10. You can do this in Java
by writing the number as a decimal value followed by an E , or an e , preceding the power of 10 that you
require. For example, the distance from the Earth to the Sun is approximately 149,600,000 kilometers,
more conveniently written as 1.496E8. Since the E (or e ) indicates that what follows is the exponent,
this is equivalent to 1.496x10 8 . At the opposite end of the scale, the mass of an electron is around
0.0000000000000000000000000009 grams. This is much more convenient, not to say more readable,
when it is written as 9.0E-28 grams.
Search WWH ::




Custom Search