Skip to content
Advertisement

How do I truncate a decimal in PHP?

I know of the PHP function floor() but that doesn’t work how I want it to in negative numbers.

This is how floor works

floor( 1234.567); //  1234
floor(-1234.567); // -1235

This is what I WANT

truncate( 1234.567); //  1234
truncate(-1234.567); // -1234

Is there a PHP function that will return -1234?

I know I could do this but I’m hoping for a single built-in function

$num = -1234.567;
echo $num >= 0 ? floor($num) : ceil($num);

Advertisement

Answer

Yes intval

intval(1234.567);
intval(-1234.567);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement