问题
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.
回答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
回答2:
<?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);
}
来源:https://stackoverflow.com/questions/34301121/remove-a-decimal-place-in-php