PHP舍入数字与数组中最接近的值

时间:2013-07-22 12:26:25

标签: php numbers

让我说我有一个

$possibleTaxes = array(7,8,13,23);

然后我有一些像13.05186.5等的值。我需要的函数会返回给定数字舍入到给定数组中最接近的值,所以:

roundToValues(19,$possibleTaxes) //returns 23
roundToValues(16,$possibleTaxes) //returns 13

另外一个选项只能舍入到更大的值,即使越小越好也是好的

4 个答案:

答案 0 :(得分:1)

尝试一次

function roundToValues($search, $possibleTaxes) {
$closest = null;
foreach($possibleTaxes as $item) {
  if($closest == null || abs($search - $closest) < abs($item - $search)) {
     $closest = $item;
  }
  }
 return $closest;
}

答案 1 :(得分:0)

仅舍入到更大的值:

<?php
function roundToValues($target, $possibleTaxes)
{
    rsort($possibleTaxes);
    $index = 0;
    foreach ($possibleTaxes as $i => $value)
    {
        if ($value < $target)
        {
            break;
        }
        else
        {
            $index = $i;
        }
    }
    return $possibleTaxes[$index];
}
$possibleTaxes = array(7,8,13,23);
echo roundToValues(19,$possibleTaxes), "\n"; // output 23
echo roundToValues(11,$possibleTaxes), "\n";// output 13

答案 2 :(得分:0)

您只需找到数字与数组中每个数字之间的绝对差异。然后取最小差异的数字。

function roundToValues( $tax, array $possibleTaxes ) {
    $differences = array();
    foreach( $possibleTaxes as $possibleTax) {
        $differences[ $possibleTax ] = abs($possibleTax - $tax);
    }
    return array_search(min($differences), $differences);
}

PHPFiddle working example

答案 3 :(得分:0)

function roundToValues($no,$possibleTaxes){

            array_push($possibleTaxes,$no);  
            sort($possibleTaxes); 
            $x=array_search($no,$possibleTaxes); 
            if(($no-@$possibleTaxes[$x-1]) > (@$possibleTaxes[$x+1]-$no) ){ 
                return @$possibleTaxes[$x+1];
            } else {
                return @$possibleTaxes[$x-1];
            } 



}

$possibleTaxes = array(7,8,13,23);
echo roundToValues(16,$possibleTaxes);