How do I truncate a decimal in PHP?
Solution 1
Yes intval
intval(1234.567);
intval(-1234.567);
Solution 2
Truncate floats with specific precision:
echo bcdiv(2.56789, 1, 1); // 2.5
echo bcdiv(2.56789, 1, 3); // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 3); // -2.567
This method solve the problem with round()
function.
Solution 3
Also you can use typecasting (no need to use functions),
(int) 1234.567; // 1234
(int) -1234.567; // -1234
http://php.net/manual/en/language.types.type-juggling.php
You can see the difference between intval
and (int)
typecasting from here.
Solution 4
another hack is using prefix ~~
:
echo ~~1234.567; // 1234
echo ~~-1234.567; // 1234
it's simpler and faster
Tilde ~
is bitwise NOT operator in PHP and Javascript
Double tilde(~
) is a quick way to cast variable as integer, where it is called 'two tildes' to indicate a form of double negation.
It removes everything after the decimal point because the bitwise operators implicitly convert their operands to signed 32-bit integers. This works whether the operands are (floating-point) numbers or strings, and the result is a number
reference:
Solution 5
you can use intval(number); but if your number bigger than 2147483648 (and your machine/os is x64) all bigs will be truncated to 2147483648. So you can use
if($number < 0 )
$res = round($number);
else
$res = floor($number);
echo $res;
chrislondon
Updated on July 07, 2021Comments
-
chrislondon almost 3 years
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);
-
chrislondon almost 11 yearsI like this because
intval
is indicative of what I'm really trying to accomplish. -
Rich Bradshaw almost 11 yearsThat's not what he wants though. Both lines should be 1234 in his example.
-
Nikhil Mohan almost 11 years@Rich Bradshaw Sry.. it's my mistake. I just copied the first code block and forgot to edit the commented part. Live demo here codepad.org/7gBgAHBK
-
chrislondon almost 11 yearsI wish I could mark two answers as correct. I like both
intval()
and(int)
-
Nikhil Mohan almost 11 years@chrislondon That's ok :). But you should check this wiki.phpbb.com/Best_Practices:PHP#Typecasting
-
Rich Bradshaw almost 11 yearsI'd typically use these functions rather than intval.
-
vr_driver almost 4 yearsThis is good if you have the library to open, otherwise you'll get a fatal error: "Call to undefined function bcdiv()"