Aggiungere un punto decimale 2 caratteri da destra sotto PHP
Domanda
Ho una grande array contenente molti elementi contenenti dati numerici.
Esempio:
3200
34300
1499
12899
voglio convertire questi in:
32.00
343.00
14.99
128.99
Come posso ottenere questo elegantemente sotto PHP senza usare regex?
Grazie in anticipo.
Soluzione
$new_array=array();
foreach($old_array as $value)
{
$new_array[]=number_format(($value/100),2);
}
number_format se si vuole perdere tempo con le migliaia separatore o qualcosa del genere. Vedere foreach se si desidera modificare i valori array in posizione.
Altri suggerimenti
In alternativa, se ti piace funzioni anonime e 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 )
Ancora e tutti, la risposta è la stessa:. Utilizzare 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);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow