example: 1.123 =>1 1.999 => 1
thanks.
You can remove trailing zeros using TRIM() function.
$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.
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.
$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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With