how can i format numbers in a php array?

10,939

Solution 1

you can try for example

$number =15.1; 
$formated = number_format($number,2);

now $formated will be 15.10

Solution 2

You can use number_format() as a map function to array_map()

$array = array(1,2,3,4,5.1);
$formatted_array = array_map(function($num){return number_format($num,2);}, $array);

Solution 3

$formatted = sprintf("%.2f", $number);

Solution 4

use the number_format function before entering values into array :

number_format($number, 2)
//will change 7 to 7.00
Share:
10,939
Kristian Rafteseth
Author by

Kristian Rafteseth

SEO Google optimaliserte nettbutikker og nettsider fra Smashup Media

Updated on June 25, 2022

Comments

  • Kristian Rafteseth
    Kristian Rafteseth almost 2 years

    Im putting values into an array. example values:

    14
    15.1
    14.12
    

    I want them all to have 2 decimals. meaning, i want the output of the array to be

    14.00
    15.10
    14.12
    

    How is this easiest achieved? Is it possible to make the array automatically convert the numbers into 2 decimalplaces? Or do I need to add the extra decimals at output-time?

  • Michael Berkowski
    Michael Berkowski over 12 years
    @diEcho Because this method is efficient and a valuable skill to learn. The OP can apply this knowledge to future situations that may be more complicated than a simple number formatting.
  • Rookie
    Rookie over 12 years
    array_map() isnt any more efficient, actually its more inefficient since its first copying the whole array, then looping through it. i would just loop through the array and be done with it. i wouldnt call array_map() a valuable skill either... just confuses newbies making them think thats the only and the only way to handle with arrays. it can be "useful" in some rare cases though... but i personally hate having too many helper functions that clutters the language into one-liner piece of... you know.
  • Mathieu Dumoulin
    Mathieu Dumoulin over 12 years
    @Rookie: Unless you do a for($i), all array functions will "copy" the data, but note that copying in php memory is very simple, it's just references until there is a change, so an array_map that just reads data doesn't really affect performance or memory, but as soon as you change something in the "copy" it gets really copied.
  • Rookie
    Rookie over 12 years
    @MathieuDumoulin, i benchmarked again, for loop 6x faster. you can try it yourself. just remember to make the array big enough, smaller arrays its not noticeable ofc.
  • The Thirsty Ape
    The Thirsty Ape almost 11 years
    To use with an array possibly try vsprintf("%.2f", $numbers_array)