In PHP, I am getting numbers from a database with 3 decimal places. I want to remove the last decimal point. So 2.112 will become 2.11, 23.123 will become 23.12 and 123.267 will become 123.26. Its like doing a floor at a decimal level.
Asked
Active
Viewed 3,339 times
2 Answers
1
You can use number_format
, you specify the number of decimal places as the second arugment.
Example
$number = 534.333;
echo number_format($number,2) // outputs 534.33
Or use round
$number = 549.333;
echo round($number, 2) // outputs 534.33
Seems like substr
is what solved the question in the end
substr($number,0,-1); // everything besides the last decimal

Antonio Smoljan
- 2,187
- 1
- 12
- 11
-
Using number_format a number like 534.386 will become 534.39. I want it to become 534.38. – Justin Dec 15 '15 at 23:13
-
So you just want to remove the last digit, something like `substr($number,0,-1);` will work fine in that case – Antonio Smoljan Dec 15 '15 at 23:19
0
<?php
$a = floor($a*100)/100;
So you can do something like that:
<?php
// Note might overflow so need some checks
function round_floor($number, $decimals) {
$n = pow(10, $decimals);
return floor($number * $decimals)/$decimals;
}
echo round_floor(2.344, 2); // Would output 2.34
echo round_floor(2.344, 1); // Would output 2.3
Another option if numbers are large:
<?php
// $decimal should be positive
function round_floor($number, $decimals) {
$a = strstr($number, '.', true);
$b = strstr($number, '.');
return $a . substr($b, 0, $decimal -1);
}

E_p
- 3,136
- 16
- 28