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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With