如何四舍五入为小数:
例如:
if decimals range from 0.26 to 0.74 I need to round to 0.50
if decimals range from 0.75 to 1.25 I need to round to 1.00
我该如何实现?
答案 0 :(得分:2)
您可以尝试以下操作:
function customRound($number) {
// extract integer part out of the number
$int_part = (int)$number;
// extract decimal part
$dec_part = (float)($number - $int_part);
$dec_rounded = 0;
if ($dec_part >= 0.26 && $dec_part < 0.75 ) {
$dec_rounded = 0.5;
} elseif ($dec_part >= 0.75) {
$dec_rounded = 1.0;
}
return $int_part + $dec_rounded;
}
答案 1 :(得分:0)
我在这里给出一个替代示例:
function customRound($number)
{
// Extract integer part out of the number.
$int_part = (int)$number;
// Extract decimal part from the number.
$dec_part = (float)($number - $int_part);
// Make the custom round on the decimal part.
$dec_rounded = $dec_part >= 0.75 ? 1.0 : ($dec_part >= 0.26 ? 0.5 : 0.0);
return $int_part + $dec_rounded;
}