Sub topic 5
Floating-Point Numbers: float and double
Sometimes a program needs numbers with fractional parts, such as a temperature of 20.5 degrees. Java provides two primitive types for these values: float and double. A primitive type is a basic Java type that holds a value directly.
Both are floating-point types. A floating-point number stores an approximation of a number using a limited amount of space. It can represent very large and very small values, but not every value exactly.
Comparing the types
A bit is a unit of stored information that can be either 0 or 1.
| Type | Bits used | Approximate precision |
|---|---|---|
| `float` | 32 | 6–7 significant decimal digits |
| `double` | 64 | 15–16 significant decimal digits |
Precision describes how much detail a stored number can keep. Significant digits are the digits that show that detail, starting with the first nonzero digit. For example, 12.345 has five significant digits. This is not the same as the number of digits after the decimal point.
These digit counts are approximate, not a promise that every decimal number will be stored exactly.
Write floating-point values
A literal is a value written directly in code. A decimal literal such as 20.5 is a double by default. To write a float literal, add f or F to the end, as in 20.5f.
Try this program:
class FloatingExample {
public static void main(String[] args) {
float temperature = 20.5f;
float shortValue = 1.23456789012345f;
double detailedValue = 1.23456789012345;
System.out.println(temperature);
System.out.println(shortValue);
System.out.println(detailedValue);
}
}Save it as FloatingExample.java. In a terminal, a window where you enter commands, run:
javac FloatingExample.java
java FloatingExampleThe first command translates the program; the second runs it. The output is:
20.5
1.2345679
1.23456789012345The float named shortValue cannot keep all the digits that were written. The printed value shows fewer digits. The double keeps more detail, although its stored value is also an approximation.
Choosing between them
Choose double for most fractional values. Its extra precision makes it a useful default. Choose float when saving memory matters and fewer digits are enough, such as when storing a large collection of approximate measurements.
Neither type is ideal for exact money calculations. Java stores floating-point values using binary, a number system based on 0 and 1. Many decimal fractions cannot be stored exactly in binary. For money, consider Java’s BigDecimal, a tool for decimal arithmetic.
Practice
Exercise
You want to store an approximate temperature in a float. How would you declare it with the value 18.5?
Show answer
Write float temperature = 18.5f; The f makes the literal a float.
Exercise
Which type is the usual choice when you need more precision for a fractional measurement?
Show answer
Choose double. It keeps about 15–16 significant decimal digits, compared with about 6–7 for float.