回合5和9 php

时间:2016-03-17 11:09:44

标签: php

我正在寻找一个公式,如果val小于5,则将值舍入为最接近的5或9,如果大于5,则为5。

示例:

$RoundToFive = ceil('232' / 5) * 5;
echo floor($RoundToFive  * 2 ) / 2; //Result is 235 Is good

$RoundToNine = ceil('236' / 5) * 5;
echo floor($RoundToNine  * 2 ) / 2; //Result is 240 but i need 239

有没有办法提取最后2位数并转换为5或9?

感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

怎么样:

function funnyRound($number){
    $rounded = ceil($number / 5) * 5;
    return $rounded%10?$rounded:$rounded-1;
}

答案 1 :(得分:0)

这是有效的

<?php
function roundToDigits($num, $suffix, $type = 'floor') {
    $pow = pow(10, floor(log($suffix, 10) + 1));
    return $type(($num - $suffix) / $pow) * $pow + $suffix; 
};
$RoundToNine = ceil('236' / 5) * 5;
echo roundToDigits($RoundToNine,5);
echo roundToDigits($RoundToNine,9);

您可以使用任何数字作为$后缀来围绕它。

答案 2 :(得分:0)

其他方式,使用字符串......:

<?php

function round59($NUMB){

    //cast the value to be Int
    $NUMB = intval($NUMB);

    //Get last number
    $last_number = intval(substr($NUMB, -1)); 

    $ROUND_NUMBER = 5;
    if($last_number<=5)
        $ROUND_NUMBER = 5;
    else
        $ROUND_NUMBER = 9;

    //Remove Last Character
    $NUMB = substr($NUMB, 0, -1);

    // now concat the results 
    return intval($NUMB."".$ROUND_NUMBER) ; 
} 

echo round59(232);
echo round59(236);
?>