在插入时,数组的圆形()内容达到特定的精度水平?

时间:2018-02-11 17:00:57

标签: php

我有一个包含类似内容的数组

$numbers = array(0.49882,0.20510,0.50669,0.20337,0.45878,0.08703,0.43491,0.74491,0.26344,0.37994);

我需要将implode()上面的数组放入一个字符串中,每个数字都舍入为2位精度。

我如何以最有效的方式实现这一目标,因为数组中可能有数百个数字?

3 个答案:

答案 0 :(得分:2)

使用array_map中的函数:

$numbers = array_map(function($v) { return round($v, 2); }, $numbers)

答案 1 :(得分:2)

您可以在implode()之前使用pygame.Rect

$numbers = array(0.49882,0.20510,0.50669,0.20337,0.45878,0.08703,0.43491,0.74491,0.26344,0.37994);
$serial = implode(',', array_map(function($v){return round($v,2);}, $numbers)) ;
echo $serial ; // 0.5,0.21,0.51,0.2,0.46,0.09,0.43,0.74,0.26,0.38

或使用number_format()

$serial = implode(',', array_map(function($v){return number_format($v,2);}, $numbers)) ;
// 0.50,0.21,0.51,0.20,0.46,0.09,0.43,0.74,0.26,0.38

答案 2 :(得分:2)

您还可以使用array_walk(),它将第二个参数中的函数应用于数组中的每个元素:

<?php
$numbers = array(0.49882,0.20510,0.50669,0.20337,0.45878,0.08703,0.43491,0.74491,0.26344,0.37994);
array_walk($numbers, function (&$el) {
    $el = round($el, 2);
});
var_dump($numbers);
echo implode(", ", $numbers);

请注意,您需要传递回调函数参数by reference才能修改实际元素而不是副本。

结果:

array (size=10)
  0 => float 0.5
  1 => float 0.21
  2 => float 0.51
  3 => float 0.2
  4 => float 0.46
  5 => float 0.09
  6 => float 0.43
  7 => float 0.74
  8 => float 0.26
  9 => float 0.38

0.5, 0.21, 0.51, 0.2, 0.46, 0.09, 0.43, 0.74, 0.26, 0.38

Demo