假设我有一个
$possibleTaxes = array(7,8,13,23);
然后我有一些值,如,13.05
等。我需要一个函数,它将返回给定数字的四舍五入到给定数组中最接近的值,所以:18
6.5
roundToValues(19,$possibleTaxes) //returns 23
roundToValues(16,$possibleTaxes) //returns 13
还可以选择仅舍入到更大的值,即使更小更接近也会很好
试试这个
function roundToValues($search, $possibleTaxes) {
$closest = null;
foreach($possibleTaxes as $item) {
if($closest == null || abs($search - $closest) < abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
仅舍入到更大的值:
<?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
你只需要找到你的数字和数组中每个数字之间的绝对差。然后取差值最小的那个数。
function roundToValues( $tax, array $possibleTaxes ) {
$differences = array();
foreach( $possibleTaxes as $possibleTax) {
$differences[ $possibleTax ] = abs($possibleTax - $tax);
}
return array_search(min($differences), $differences);
}
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);