问题
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
回答1:
Taking your question literally, this will do it:
$value = (round($original_value / 0.05, 0)) * 0.05
i.e. will round to the nearest 0.05.
If, for some reason, you want to always round up to 0.05, use
$value = (round(($original_value + 0.025) / 0.05, 0)) * 0.05
回答2:
you have 3 possibility : round(), floor(), ceil()
for you :
$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
round
<?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
?>
floor
<?php
echo floor(4.3); // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>
ceil
<?php
echo ceil(4.3); // 5
echo ceil(9.999); // 10
echo ceil(-3.14); // -3
?>
回答3:
You can use this code:
$value = 2.3333333333;
$value = round ( $value, 2, PHP_ROUND_HALF_UP);
best document is in here
回答4:
Try:
$value = 2.3333333333;
echo number_format($value, 2);
回答5:
Complementary functions to round up / down to arbitrary number of decimals:
/**
* 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;
}
}
}
来源:https://stackoverflow.com/questions/17564365/how-to-round-up-value-in-php