2014-04-16 120 views
0

四捨五入我需要一個可以圓從定義的自定義範圍...與指定的自定義範圍

例如功能:

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

回答

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]; 
     } 
    } 
} 
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; 
} 
分離開時,