Add decimal point 2 characters to the right under PHP
I have a large array containing many items containing numeric data.
Example:
3200 34300 1499 12899
I want to convert them to:
32.00
343.00
14.99
128.99
How can I achieve this elegantly in PHP without using regex?
Thanks in advance.
+2
user186515
source
to share
3 answers
$new_array=array();
foreach($old_array as $value)
{
$new_array[]=number_format(($value/100),2);
}
See number_format if you want to tinker with the thousand separator or something. See foreach if you want to change array values ββin place.
+9
ansate
source
to share
Or, if you like anonymous functions and PHP 5.3:
$ nums = array (1, 2, 3, 4); array_walk ($ nums, function (& $ val, $ key) { $ val = number_format ($ val / 100, 2); }); print_r ($ nums);
Output:
Array ( [0] => 1.00 [1] => 2.00 [2] => 3.00 [3] => 4.00 )
Still and everything, the answer is the same: use number_format()
.
+2
hlpiii
source
to share
Using number_format .
for($i=0;$i<count($array);$i++)
{
$array[$i] = number_format($array[$i]/100,2);
//if you need them as numbers
$array[$i] = (float) number_format($array[$i]/100,2);
}
0
Alan storm
source
to share