Floating-Point Data Types
What you'll learn: How computers represent decimal numbers and why they behave differently from whole numbers.
What Are Floating-Point Numbers?
In the previous lesson, you learned about integer data types that store whole numbers. But what about numbers with decimal points like 3.14, 0.5, or -2.718? These are called floating-point numbers, and computers store them using special data types.
The term "floating-point" comes from how these numbers are stored internally: the decimal point can "float" to different positions, similar to scientific notation (like 3.14 × 10²).
Common Floating-Point Types
Most programming languages offer at least two floating-point types:
float— single precision, uses less memory, roughly 6-7 decimal digits of accuracydouble— double precision, uses more memory, roughly 15-16 decimal digits of accuracy
The Precision Problem
Here's the critical thing to understand: computers cannot represent most decimal numbers exactly. Just like you can't write 1/3 exactly in decimal form (it's 0.333333... forever), computers can't represent 0.1 exactly in binary.
This leads to surprising results. A calculation like 0.1 + 0.2 might not equal exactly 0.3 — it might be 0.30000000000000004 instead! This isn't a bug; it's an inherent limitation of how floating-point arithmetic works.
When to Use Floating-Point
Use floating-point types when:
- You need decimal values (measurements, calculations)
- Slight imprecision is acceptable (graphics, science)
Avoid them when exact precision matters (like money calculations).
Key Takeaway: Floating-point types store decimal numbers but cannot represent most decimals exactly due to binary limitations, leading to small precision errors in arithmetic operations.