Floating-point values
What you will learn
Java uses float and double for binary floating-point approximations. A double has more precision than a float and is the ordinary choice for measurements. Neither represents every decimal fraction exactly.
public class Main { public static void main(String[] args) { double width = 2.5; double height = 4.0; System.out.println(width * height); }}Expected output:
10.0Both input fractions are exactly representable, and the product is 10.
How it works
A decimal literal such as 2.5 is double unless suffixed with f or F. Binary fractions such as 0.5 are exactly representable, but 0.1 is not. Floating-point arithmetic can round intermediate and final values. Use decimal arithmetic with explicit rounding rules for exact monetary calculations later in the track.
public class Main { public static void main(String[] args) { double total = 0.1 + 0.2; System.out.println(total); }}Expected output:
0.30000000000000004The closest binary representations and rounding produce this displayed result.
Common mistakes
float value = 2.5; does not compile because the literal is double. Use 2.5f for a float or declare a double. Do not treat decimal-looking output as evidence of exact decimal storage.
Try it yourself
Calculate the area of a 1.5 by 8.0 rectangle, then compare the displayed results of 0.1 + 0.2 and 0.5 + 0.25.
These are local Java practice tasks, not automatically graded ByteMind exercises. Use a patched JDK; no network or third-party dependency is needed.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Floating-point values — knowledge check
Check your understanding of floating-point values.
What is the default type of 2.5?
Why can 0.1 + 0.2 display more digits than expected?