note 54799 deleted from function.number-format by levim
| From: | levim@php.net | Date: | Sun, 23 Mar 2014 14:15:04 +0000 |
| Subject: | note 54799 deleted from function.number-format by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199022@lists.php.net to get a copy of this message | ||
Note Submitter: jarratt at si-works dot net
----
With one of the payment providers they required a monitary input of 12345.67 always with a 2 decimal
placing even if .00
if you have a number 12345.5 with only one decimal place i could find no sutable php function to
guarentee two decimal palces and add a trailing zero if required,
This fucntion should assist
function format_number($str,$decimal_places='2',$decimal_padding="0"){
/* firstly format number and shorten any extra decimal places */
/* Note this will round off the number pre-format $str if you dont want this fucntionality
*/
$str = number_format($str,$decimal_places,'.',''); //
will return 12345.67
$number = explode('.',$str);
$number[1] = (isset($number[1]))?$number[1]:''; // to fix the PHP Notice error
if str does not contain a decimal placing.
$decimal = str_pad($number[1],$decimal_places,$decimal_padding);
return (float) $number[0].'.'.$decimal;
}
/* examples */
format_number('1234'); // --> 1234.00
format_number('1234.5'); //--> 1234.50
format_number('1234.567'); //--> 1234.57