Skip to content

Core\Math::truncate

Core\Math::truncate(float $n): floatCore\Math::truncate(
    float $n,
): float

Core\Math::truncate removes the fractional part of a number. The result moves toward zero: 2.7 gives 2.0, and -2.7 gives -2.0. Core\Math::floor is different for negative numbers: it gives -3.0 for -2.7.

The result is still a float. To get an int, convert it with as int. A number between -1.0 and 0.0 gives -0.0, which is equal to 0.0. NaN (a value that means "not a number") and the infinities stay the same. Very large float values have no fractional part, so they also stay the same. Core\Math::truncate never throws an error.

The examples below show positive and negative numbers, then the special values, then a timer that shows whole seconds.

Parameters

  • $nfloatThe number whose fractional part is removed.

Return value

Returns float. A whole number, as a float. A $n between -1.0 and 0.0 gives -0.0. NaN and the infinities stay the same.

Examples

Toward zero

<?nvs
// Shows how `Core\Math::truncate` removes the fractional part of positive and negative numbers.
// This prints 2, then -2. Both results move toward zero.
echo Core\Math::truncate(2.7), "\n";
echo Core\Math::truncate(-2.7), "\n";
// `Core\Math::floor` always moves down. For -2.7 it prints -3.
echo Core\Math::floor(-2.7), "\n";
// The result is a `float`. `as int` converts it to a whole number. This prints 19.
int $whole = Core\Math::truncate(19.99) as int;
echo $whole, "\n";
Output
2
-2
-3
19

Special values

<?nvs
// Shows the result for small negative numbers, very large numbers, infinity and `NaN`.
// A number between -1.0 and 0.0 gives negative zero. This prints -0.
echo Core\Math::truncate(-0.5), "\n";
// A very large `float` has no fractional part, so it stays the same. This prints 1.0E+20.
echo Core\Math::truncate(1e20), "\n";
// Infinity and `NaN` stay the same. This prints INF, then NAN.
echo Core\Math::truncate(Core\Math::INFINITY), "\n";
echo Core\Math::truncate(Core\Math::NAN), "\n";
Output
-0
1.0E+20
INF
NAN

Timer in whole seconds

<?nvs
// Shows how a timer on a page shows only the whole seconds that have passed.
class Timer
{
// Returns the seconds as text, without the fractional part.
public static function label(float $seconds): string
{
int $whole = Core\Math::truncate($seconds) as int;
return $whole . ' s';
}
}
// This prints "0 s", "12 s" and "59 s". The timer never shows a second too early.
array<float> $readings = [0.4, 12.87, 59.99];
foreach ($readings as float $reading) {
echo Timer::label($reading), "\n";
}
Output
0 s
12 s
59 s