Floating-point Data Types
Floating-point numbers are numbers that have fractional parts (usually expressed with a decimal point). You should use a floating-point type whenever you need a number with a decimal, such as 19.95 or 3.1415.
Java has two primitive types for floating-point numbers:
float
: Uses 4 bytes
double
: Uses 8 bytes
In almost all cases, you should use the double
type whenever you need numbers with fractional values.
The precision of a floating-point value indicates how many significant digits the value can have following its decimal point. The precision of a float
type is only about six or seven decimal digits, which isn’t sufficient for most types of calculations. If you use Java to write a payroll system, for example, you might get away with using float
variables to store salaries for employees such as teachers or firefighters, but not for professional baseball players or corporate executives.
By contrast, double variables have a precision of about 15 digits, which is enough for most purposes.
double period = 99.0;
If you omit the decimal point, the Java compiler treats the literal as an integer. Then, when it sees that you’re trying to assign the integer literal to a double variable, the compiler converts the integer to a double value. This avoidable conversion step uses some precious processing time.
To save that time, you can add an F
or D
suffix to a floating-point literal to indicate whether the literal itself is of type float
or double
. For example:
float value1 = 199.33F;
double value2 = 200495.995D;
If you omit the suffix, D
is assumed. As a result, you can usually omit the D
suffix for double
literals.