Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round() contents of an array to a particular level of precision when imploding?

Tags:

php

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?

like image 959
Nithin Avatar asked Mar 07 '23 22:03

Nithin


2 Answers

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
like image 86
Syscall Avatar answered Apr 29 '23 13:04

Syscall


Use a function in array_map:

$numbers = array_map(function($v) { return round($v, 2); }, $numbers)
like image 29
AbraCadaver Avatar answered Apr 29 '23 11:04

AbraCadaver