i have value in php variable like that
$var=\'2.500000550\';
echo $var
what i want is to delete all decimal points after 2 digits.
Already a lot of possible solutions, I just want to add the one that I came up to solve my problem.
function truncate_decimals($number, $decimals=2)
{
$factor = pow(10,$decimals);
$val = intval($number*$factor)/$factor;
return $val;
}
truncate_decimals(199.9349,2);
// 199.93
number_format rounds the number
php > echo number_format(128.20512820513, 2)."\n";
128.21
I used preg_replace to really cut the string
php > echo preg_replace('/(\.\d\d).*/', '$1', 128.20512820513)."\n";
128.20
floor - not quite! (floor rounds negative numbers)
A possible solution from cale_b answer.
static public function rateFloor($rate, $decimals)
{
$div = "1" . str_repeat("0", $decimals);
if ($rate > 0) {
return floor($rate * $div) / $div;
}
$return = floor(abs($rate) * $div) / $div;
return -($return);
}
static public function rateCeil($rate, $decimals)
{
$div = "1" . str_repeat("0", $decimals);
if ($rate > 0) {
return ceil($rate * $div) / $div;
}
$return = ceil(abs($rate) * $div) / $div;
return -($return);
}
Positive
Rate: 0.00302471
Floor: 0.00302400
Ceil: 0.00302500
Negative
Rate: -0.00302471
Floor: -0.00302400
Ceil: -0.00302500