Skip to content

Core\Decimal::floor

Cuts a number down, to a whole number or to a chosen number of digits after the point.

Core\Decimal::floor always moves towards the smaller number. 2.9 becomes 2, and -2.1 becomes -3. The second argument says how many digits after the point to keep, and leaving it out gives a whole number. The result is exact, because it is a decimal and not a floating-point number.

Use it when the part you cut off is worth nothing to the person on the other side. Examples are how many whole items a budget buys, and how many full hours a job is billed for. Another is a commission cut to cents, so a shop never pays out more than the rate allows.

Good to know: Core\Decimal::ceil moves towards the larger number, and Core\Decimal::truncate removes the digits after the point. All three give the same result for a positive number. They differ for a negative number: floor(-0.4) is -1, and the other two return 0.

Parameters

  • $valuedecimalThe value to cut.
  • $scaleuintdefault 0The number of digits after the decimal point, at most 28. Without it, the result has none. The result always has exactly this many, so a shorter value is padded with zeros.

Return value

Returns decimal. The largest decimal with $scale digits that is not above $value. floor(-1.5) is -2, and floor(1.005, 2) is 1.00.

Errors

  • ArithmeticErrorWhen $scale is more than 28. Also when $value has too many digits before the point to keep that many digits after it.

Examples

Cut down to a whole number

<?nvs
// Shows how to cut a number down. `Core\Decimal::floor` always moves towards
// the smaller number.
decimal $weight = 7.95;
// With one argument the answer is a whole number. This prints 7.
echo Core\Decimal::floor($weight), "\n";
// The second argument is how many digits to keep after the point. This
// prints 7.9.
echo Core\Decimal::floor($weight, 1), "\n";
// The answer always has the number of digits you asked for, so this
// prints 7.9500.
echo Core\Decimal::floor($weight, 4), "\n";
Output
7
7.9
7.9500

A negative number goes down

<?nvs
// Shows where `Core\Decimal::floor` sends a negative number. It moves towards
// the smaller number, and -3 is smaller than -2.
array<decimal> $values = [2.7, 2.1, -2.1, -2.7];
// This prints 2, 2, -3 and -3, one on each line.
foreach ($values as decimal $value) {
echo Core\Decimal::floor($value), "\n";
}
// `Core\Decimal::truncate` cuts towards zero. For -2.7 the result is -2.
echo Core\Decimal::truncate(-2.7), "\n";
Output
2
2
-3
-3
-2

A commission cut to cents

<?nvs
// Shows how to work out a commission and cut it down to cents. Cutting down
// keeps the payout at or under the rate the shop agreed to.
array<decimal> $sales = ['ada' => 1290.45, 'kim' => 876.10, 'juno' => 42.99];
decimal $rate = 0.075;
foreach ($sales as string $seller => decimal $sold) {
decimal $commission = Core\Decimal::floor($sold * $rate, 2);
echo $seller, ': ', $commission, "\n";
}
Output
ada: 96.78
kim: 65.70
juno: 3.22