PHP: floor - Manual (original) (raw)
(PHP 4, PHP 5, PHP 7, PHP 8)
floor — Round fractions down
Description
Returns the next lowest integer value (as float) by rounding downnum if necessary.
Parameters
num
The numeric value to round
Return Values
num rounded to the next lowest integer. The return value of floor() is still of typefloat.
Changelog
| Version | Description |
|---|---|
| 8.0.0 | num no longer accepts internal objects which support numeric conversion. |
Examples
Example #1 floor() example
<?php echo floor(4.3), PHP_EOL; // 4 echo floor(9.999), PHP_EOL; // 9 echo floor(-3.14), PHP_EOL; // -4 ?>
Found A Problem?
6 years ago
<?php
echo (2.3 * 100) . ' - ' . round(2.3 * 100, 0) . ' - ' . floor(2.3 * 100);
?>.
Result:
230 - 230 - 229
Be careful!jolyon at mways dot co dot uk ¶
21 years ago
Beware of FLOAT weirdness!
Floats have a mind of their own, and what may look like an integer stored in a float isn't.
Here's a baffling example of how floor can be tripped up by this:
<?php
$price = 79.99;
print $price."\r\n"; // correct result, 79.99 shown
<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mi>r</mi><mi>i</mi><mi>c</mi><mi>e</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">price = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.854em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">i</span><span class="mord mathnormal">ce</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>price * 100;
print $price."\r\n"; // correct result, 7999 shown
print floor($price); // 7998 shown! what's going on?
?>
The thing to remember here is that the way a float stores a value makes it very easy for these kinds of things to happen. When the 79.99 was multiplied by 100, the actual value stored in the float was probably something like 7998.9999999999999999999999999999999999, PHP would print out 7999 when the value is displayed, but floor would therefore round this down to 7998.
The moral of this story - never use float for anything that needs to be accurate! If you're doing prices for products or a shopping cart, then always use an integer and store prices as a number of pence, you'll thank me for this later :)
17 years ago
Note:
<?php
$int = 0.99999999999999999;
echo floor($int); // returns 1
?>
and
<?php
$int = 0.9999999999999999;
echo floor($int); // returns 0
?>