This code:
echo (40 * (10 / 100 + 1)); //44
echo (50 * (10 / 100 + 1)); //55
echo ceil(40 * ((10 / 100) + 1)); //44
echo ceil(50 * ((10 / 100) + 1)); //56 (!)
I think, that "56" by reason of floating point (55.0000000001 => 56), but I can't understood why for "40" result is "44", not "45"
The ceil() function is a built-in function in PHP and is used to round a number to the nearest greater integer. Parameters: The ceil() function accepts a single parameter value which represents the number which you want to round up to the nearest greater integer.
Both ceil() and floor() take just one parameter - the number to round. Ceil() takes the number and rounds it to the nearest integer above its current value, whereas floor() rounds it to the nearest integer below its current value.
The 55 isn’t actually 55. You can verify that easily:
<?php
$x = (40 * (10 / 100 + 1)); // 44
$y = (50 * (10 / 100 + 1)); // 55
echo '$x == 44: ' . ($x == 44 ? 'True' : 'False') . "\n";
echo '$y == 55: ' . ($y == 55 ? 'True' : 'False') . "\n";
echo '$y > 55: ' . ($y > 55 ? 'True' : 'False') . "\n";
echo $y - 55;
Yields:
$x == 44: True
$y == 55: False
$y > 55: True
7.105427357601E-15
As you can see the difference is tiny (7.1 * 10^-15) but that still makes it larger than 55, so ceil
will round it up.
The reason you just see 55
is because echoing it will convert the float into a string:
String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo or print functions, or when a variable is compared to a string.
For this conversion the standard truncating behavior will cut off the digits at some point. This is configured by the precision
configuration parameter and defaults to 14. You can avoid this behavior by using sprintf
with a custom precision:
echo sprintf('%.50f', $y);
// 55.00000000000000710542735760100185871124267578125000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With