In PHP, you can get the integer part of a decimal number in the following ways:
If you wish to perform division and get the integer value as a result, then you may also use intdiv()
.
Casting to Integer
You can cast the number to an integer (or use the intval()
function) to truncate floating point numbers towards zero, discarding the fractional component of a number and returning only the integer part.
For example, you can use it like this:
var_dump((int) (10 / 3)); // 3 var_dump((int) (-10 / 3)); // -3 var_dump((int) (10 / -3)); // -3 var_dump((int) 3.333); // 3 var_dump((int) -3.333); // -3
var_dump((int) (5 / 2)); // 2 var_dump((int) (-5 / 2)); // -2 var_dump((int) (5 / -2)); // -2 var_dump((int) 2.5); // 2 var_dump((int) -2.5); // -2
var_dump((int) (10 / 1)); // 10 var_dump((int) (-10 / 1)); // -10 var_dump((int) (10 / -1)); // -10 var_dump((int) 10.0); // 10 var_dump((int) -10.0); // -10
Using floor()
and ceil()
To achieve the same effect as with casting to integer, you can:
- Use
floor()
to round down positive integers, and; - Use
ceil()
to round up negative integers.
Doing so would truncate a floating point number towards zero. You can implement it, for example, like so:
function trunc(int|float $num): int { return ($num > 0) ? floor($num) : ceil($num); }
You can also implement this using only the floor()
function like so:
function trunc(int|float $num): int { $unsignedNum = floor(abs($num)); return ($num < 0) ? -$unsignedNum : $unsignedNum; }
Similarly, you can implement this using only the ceil()
function like so:
function trunc(int|float $num): int { $unsignedNum = ceil(-abs($num)); return ($num < 0) ? $unsignedNum : -$unsignedNum; }
Using any of these would yield the same result (as you can see in the examples below):
var_dump(trunc(10 / 3)); // 3 var_dump(trunc(-10 / 3)); // -3 var_dump(trunc(10 / -3)); // -3 var_dump(trunc(3.333)); // 3 var_dump(trunc(-3.333)); // -3
var_dump(trunc(5 / 2)); // 2 var_dump(trunc(-5 / 2)); // -2 var_dump(trunc(5 / -2)); // -2 var_dump(trunc(2.5)); // 2 var_dump(trunc(-2.5)); // -2
var_dump(trunc(10 / 1)); // 10 var_dump(trunc(-10 / 1)); // -10 var_dump(trunc(10 / -1)); // -10 var_dump(trunc(10.0)); // 10 var_dump(trunc(-10.0)); // -10
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.