在laravel中将数字四舍五入到最接近的9

时间:2020-12-21 11:44:48

标签: php laravel

我想把一个数字四舍五入到最接近的 9,这是一个例子

(12,24,37,75,80)

如果我给了这个输入想要得到如下给出的输出

(19,29,39,79,89)

我正在使用 PHP(laravel),请帮帮我。

3 个答案:

答案 0 :(得分:4)

$input = [12,24,37,75,80];

$output = array_map(function($num) {
    return (int)($num / 10) * 10 + 9;
}, $input);

答案 1 :(得分:1)

我喜欢@HTMHell 的简单回答。它适用于整数。但是,我发现,当使用实数作为输入时,诸如 19.999 之类的内容将被“四舍五入”为 19

因此,我建议使用以下修改版本:

echo json_encode(array_map(function($v){
  return ceil(($v+1)/10)*10-1;
},[12,18.99,19.01,24,37,75,80,90]));
// [19,19,29,29,39,79,89,99]

而且,要回答@nice_dev 的问题,90 应该四舍五入为 99

答案 2 :(得分:0)

<?php 

$items = array(12,24,37,75,80);
$endDigit = 9; //this should be between 0-9
$newItems = array();
foreach($items as $item){
  $final = (int)($item / 10) * 10 + $endDigit;
  array_push($newItems,$final); 
}
print_r($newItems);

输出

Array ( [0] => 19 [1] => 29 [2] => 39 [3] => 79 [4] => 89 )