I have a value like this:
$value = 2.3333333333;
and I want to round up this value into like this:
$value = 2.35;
I already tried round, ceil and etc but the result is not what I expected.
Please anyone help.
Thanks
你有 3 种可能性:round(), floor(), ceil()
为你 :
$step = 2; // number of step 3th digit
$nbr = round(2.333333333 * $step, 1) / $step; // 2.35
$step = 4; // number of step on 3th digit
$nbr = round(2.333333333 * $step, 1) / $step; // 2.325
<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>
<?php
echo floor(4.3); // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>
<?php
echo ceil(4.3); // 5
echo ceil(9.999); // 10
echo ceil(-3.14); // -3
?>
从字面上理解你的问题,这将做到:
$value = (round($original_value / 0.05, 0)) * 0.05
ie 将四舍五入到最接近的0.05。
如果出于某种原因,您希望始终向上舍入到 0.05,请使用
$value = (round(($original_value + 0.025) / 0.05, 0)) * 0.05
向上/向下舍入到任意小数位数的补充函数:
/**
* Round up to specified number of decimal places
* @param float $float The number to round up
* @param int $dec How many decimals
*/
function roundup($float, $dec = 2){
if ($dec == 0) {
if ($float < 0) {
return floor($float);
} else {
return ceil($float);
}
} else {
$d = pow(10, $dec);
if ($float < 0) {
return floor($float * $d) / $d;
} else {
return ceil($float * $d) / $d;
}
}
}
/**
* Round down to specified number of decimal places
* @param float $float The number to round down
* @param int $dec How many decimals
*/
function rounddown($float, $dec = 2){
if ($dec == 0) {
if ($float < 0) {
return ceil($float);
} else {
return floor($float);
}
} else {
$d = pow(10, $dec);
if ($float < 0) {
return ceil($float * $d) / $d;
} else {
return floor($float * $d) / $d;
}
}
}
尝试:
$value = 2.3333333333;
echo number_format($value, 2);