Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all numbers after point in PHP

Tags:

php

example: 1.123 =>1 1.999 => 1

thanks.

like image 636
lovespring Avatar asked May 15 '10 17:05

lovespring


People also ask

How remove extra zeros from decimal in PHP?

You can remove trailing zeros using TRIM() function.

How can I get only 2 decimal places in PHP?

$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Save this answer.

How do you round down in PHP?

The floor() function rounds a number DOWN to the nearest integer, if necessary, and returns the result. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a floating-point number, look at the round() function.


2 Answers

$y = 1.235251;
$x = (int)$y;
echo $x; //will echo "1"

Edit: Using the explicit cast to (int) is the most efficient way to to this AFAIK. Also casting to (int) will cut off the digits after the "." if the number is negative instead of rounding to the next lower negative number:

echo (int)(-3.75); //echoes "-3";
echo floor(-3.75); //echoes "-4";
like image 71
selfawaresoup Avatar answered Oct 14 '22 07:10

selfawaresoup


floor() 

will round a number down to the nearest integer.

EDIT: As pointed out by Mark below, this will only work for positive values, which is an important assumption. For negative values, you'd want to use ceil() -- but checking the sign of the input value would be cumbersome and you'd probably want to employ Mark's or TechnoP's (int) cast idea instead. Hope that helps.

like image 25
LesterDove Avatar answered Oct 14 '22 06:10

LesterDove