简体   繁体   中英

rounding with specified custom range

i need a function that can round from a defined custom range...

for example:

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

i tried something but doesn't work at all...

code:

$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);

Sounds like you should just write your own code for this function...

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];
        }
    }
}

You could easily multiply times 100 then find modulus value left when dividing by 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;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM