使用指定的自定义范围进行舍入

时间:2014-04-16 16:52:15

标签: php

我需要一个可以定义自定义范围的函数...

例如:

0.01 - 0.39 = round to 0
0.40 - 0.74 = round to 0.5
0.75 - 0.99 = round to 1

if number is 2.33 it should show as 2.0
if number is 2.67 it should show as 2.5
if number is 2.89 it should show as 3.0

我尝试了一些但根本不起作用......

代码:

$range1 = range(0.01, 0.39, 0.01);
$range2 = range(0.40, 0.74, 0.01);
$range3 = range(0.75, 0.99, 0.01);

function round_range($num) {
    global $range1, $range2, $range3;

    if (in_array($num, $range1))
        return round($num, 0, PHP_ROUND_HALF_DOWN);
    else if (in_array($num, $range2))
        return round($num, 0, PHP_ROUND_HALF_DOWN);
    else if (in_array($num, $range3))
        return round($num, 0, PHP_ROUND_HALF_DOWN);
    else
        return "error";
}

echo round_range(0.35);

2 个答案:

答案 0 :(得分:1)

听起来你应该为这个函数编写自己的代码......

public function roundWithDefinedRange($num) {
    $rangeDefinitions = array (
        array ( array ( 0.01, 0.39 ) , 0 ),
        array ( array ( 0.40, 0.74 ) , 0.5 ),
        array ( array ( 0.75, 0.99 ) , 1 ),
    );

    $decimal = $num - floor($num);

    foreach ($rangeDefinitions as $range) {
        if ($decimal >= $range[0][0] && $decimal <= $range[0][1]) {
            return floor($num)+$range[1];
        }
    }
}

答案 1 :(得分:0)

您可以轻松地乘以100然后在除以100

时找到剩余的模数值
function round_range($num) {
    $num_times_100 = $num * 100;
    $modulus = $num_time_100 % 100;
    $base = $num - $modulus;
    $round = 0;
    if($modulus >= 0.4 && $modulus < 0.75) {
        $round = 0.5;
    } else if ($modulus >= 0.75) {
        $round = 1;
    }
    return $base + $round;
}