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

I have an array with contents like such

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

I need to implode() the above array into a string with each number rounded to 2 digit precision.

How do i achieve this in the most efficient way possible as there might be hundreds of numbers in the array?

You could use array_map() before to implode():

$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

Or using 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

Use a function in array_map:

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

You can also use array_walk(), which will apply the function in the second argument to each element in the array:

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

Note that you need to pass the callback function argument by reference in order to modify the actual element and not a copy.

Result:

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