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?
$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.
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 )
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.
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);
you can try for example
$number =15.1;
$formated = number_format($number,2);
now $formated will be 15.10
$formatted = sprintf("%.2f", $number);
use the number_format function before entering values into array :
number_format($number, 2)
//will change 7 to 7.00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With