0
0
PHPprogramming~20 mins

Float type and precision in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Float Precision Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP float addition?

Consider the following PHP code:

$a = 0.1 + 0.2;
echo $a === 0.3 ? 'Equal' : 'Not equal';

What will be printed?

PHP
$a = 0.1 + 0.2;
echo $a === 0.3 ? 'Equal' : 'Not equal';
ANot equal
BEqual
C0.3
DError
Attempts:
2 left
💡 Hint

Think about how floating point numbers are stored in computers.

Predict Output
intermediate
2:00remaining
What is the output of this float formatting code?

What does this PHP code output?

$num = 1.23456789;
echo number_format($num, 4);
PHP
$num = 1.23456789;
echo number_format($num, 4);
A1.2346
B1.2345
C1.23456789
D1.234
Attempts:
2 left
💡 Hint

number_format rounds the number to the specified decimals.

🔧 Debug
advanced
2:30remaining
Why does this float comparison fail?

Examine this PHP code snippet:

$x = 0.15 + 0.15;
$y = 0.1 + 0.2;
if ($x == $y) {
    echo 'Equal';
} else {
    echo 'Not equal';
}

Why does it print 'Not equal'?

PHP
$x = 0.15 + 0.15;
$y = 0.1 + 0.2;
if ($x == $y) {
    echo 'Equal';
} else {
    echo 'Not equal';
}
ABecause both sums are exactly equal but the code has a syntax error
BBecause 0.1 + 0.2 is exactly 0.3 but 0.15 + 0.15 is not
CBecause PHP does not support float addition
DBecause 0.15 + 0.15 is exactly 0.3 but 0.1 + 0.2 is not
Attempts:
2 left
💡 Hint

Try printing the values of $x and $y with high precision.

📝 Syntax
advanced
1:30remaining
Which option causes a syntax error with float literals?

Which of the following PHP code snippets will cause a syntax error?

A$num = 0.5;
B$num = 1.2e3;
C$num = 1.2.3;
D$num = 2e-2;
Attempts:
2 left
💡 Hint

Look carefully at the float literal formats.

🚀 Application
expert
2:30remaining
How many items are in the array after float keys are used?

What is the number of elements in this PHP array?

$arr = [];
$arr[1.0] = 'a';
$arr[1.00] = 'b';
$arr[1.000] = 'c';
echo count($arr);
PHP
$arr = [];
$arr[1.0] = 'a';
$arr[1.00] = 'b';
$arr[1.000] = 'c';
echo count($arr);
AError
B1
C3
D0
Attempts:
2 left
💡 Hint

Think about how PHP treats float keys in arrays.