Kristian Rafteseth
Kristian Rafteseth

Reputation: 2032

how can i format numbers in a php array?

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?

Upvotes: 5

Views: 13641

Answers (4)

Rookie
Rookie

Reputation: 3793

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

Upvotes: 2

salahy
salahy

Reputation: 1197

you can try for example

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

now $formated will be 15.10

Upvotes: 3

Abhinav Pandey
Abhinav Pandey

Reputation: 499

use the number_format function before entering values into array :

number_format($number, 2)
//will change 7 to 7.00

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270637

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);

Upvotes: 25

Related Questions