I would like to create a rounding methode to round decimals always up to the closest highest decimal value.
for example: 51.13 => 51.20 or 22.33 => 23.40
but lets say 30.10 stays 30.10
Is this even possible? Sorry if my explonation is bad but my math english is not the best.
maybe custom function for rounding ?
something like this
$inputNumber=51.13;
function round2deci($number){
$explode = explode(".", $number);
/// 51.13 == 51.ab
$a = substr($explode[1], 0, 1);
$b = substr($explode[1], 1, 2);
// fix for 51.91
if($a == 9){
$explode[0]++;
$a = 0;
$b = 0;
}
if($b > 0){
$a++;
}
echo $explode[0].".".$a."0";
}
round2deci($inputNumber);
and result is :
51.20
I found this answer on the php.net website under the ceil
docs that does exactly what you want.
I've added an improved version below which returns a pure float where you'd be able to apply number_format
to preserve the trailing zeros of the decimals:
function ceil_dec(float $number, int $precision = 2, string $separator = '.') : float
{
$numberpart = explode($separator, (string)$number);
$numberpart[1] = substr_replace($numberpart[1], $separator, $precision, 0);
if ($numberpart[0] >= 0) {
$numberpart[1] = ceil($numberpart[1]);
} else {
$numberpart[1] = floor($numberpart[1]);
}
$ceil_number = [$numberpart[0], $numberpart[1]];
return (float)implode($separator, $ceil_number);
}
var_dump(
ceil_dec(10.23,1)
);
The above code is good for PHP 7.0 and above, and with declare(strict_types = 1)
enabled.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.