How to remove all numbers after a dot in PHP

example: 1.123 => 1 1.999 => 1

thanks.

+6
php
source share
5 answers
floor() 

rounds a number to the nearest integer.

EDIT: As indicated by Mark below, this will only work for positive values, which is an important assumption. For negative values, you want to use ceil() , but checking the sign of the input value will be cumbersome, and you probably want to use the idea of ​​Mark or TechnoP (int) cast . Hope this helps.

+18
source share
 $y = 1.235251; $x = (int)$y; echo $x; //will echo "1" 

Edit: Using explicit casts in (int) is the most efficient way for this AFAIK. Also, clicking on (int) will turn off the numbers after the ".". if the number is negative, and not rounding to the next lower negative number:

 echo (int)(-3.75); //echoes "-3"; echo floor(-3.75); //echoes "-4"; 
+22
source share
 $y = 1.234; list($y) = explode(".", "$y"); 
+2
source share

If your input can only be a positive float, then, as already mentioned, the floor works.

 floor(1.2) 

However, if your integer may also be negative, then the gender may not give you what you want: it is always rounded even for negative numbers. Instead, you can use int as the other mentioned message. This will give you the correct result for both negative and positive numbers.

 (int)-1.2 
+2
source share

You can use the bitwise operator.

Without:

 echo 49 / 3; >> 16.333333333333 

With " | 0 " bitwise:

 echo 49 / 3 | 0; >> 16 
+2
source share

All Articles