Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i format numbers in a php array?

Tags:

php

formatting

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?

like image 429
Kristian Rafteseth Avatar asked Oct 01 '11 11:10

Kristian Rafteseth


People also ask

How can I get only 2 decimal places in PHP?

$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Save this answer.

What is number format PHP?

The number_format() function is an inbuilt function in PHP which is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure. Syntax: string number_format ( $number, $decimals, $decimalpoint, $sep )

Can PHP array have different data types?

According to the PHP manual you can indeed store heterogeneous types inside a PHP "array" - scroll down to example 3. Note that even though the example is about keys being ints or strings, the values assigned in the example are also both ints and strings, demonstrating that it is possible to store heterogeneous types.


4 Answers

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);
like image 166
Michael Berkowski Avatar answered Oct 04 '22 02:10

Michael Berkowski


you can try for example

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

now $formated will be 15.10

like image 22
salahy Avatar answered Oct 04 '22 03:10

salahy


$formatted = sprintf("%.2f", $number);
like image 40
Rookie Avatar answered Oct 04 '22 02:10

Rookie


use the number_format function before entering values into array :

number_format($number, 2)
//will change 7 to 7.00
like image 22
Abhinav Pandey Avatar answered Oct 04 '22 04:10

Abhinav Pandey