PHP Basics · Lesson 5 of 8
Floats
Represent decimal measurements and understand floating-point precision.
Lesson
Floats represent approximate real numbers. Binary floating-point cannot exactly store many decimal fractions, so a direct equality comparison can surprise you. For money, store integer minor units such as cents or use a decimal arithmetic library; round only at a deliberate presentation or business-rule boundary.
The example uses a tolerance when comparing approximate measurements rather than expecting exact equality.
Further guidance
Inspect a value before relying on an implicit conversion. Keep input validation separate from casting, use strict comparisons when type matters, and choose an explicit representation for values such as money or optional data. Try normal, empty, and unexpected inputs so the result is deliberate.
Practice task: Create a fresh example for Floats. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
Floats
PHP
$measured = 0.1 + 0.2;
$expected = 0.3;
var_export(abs($measured - $expected) < 0.000001);
Expected output
true
Key points
- Represent decimal measurements and understand floating-point precision.
- Validate external data before converting or using it.
- Use strict comparisons when both value and type matter.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.