note 87381 added to function.number-format
| From: | nospam at nospam dot com | Date: | Tue, 02 Dec 2008 22:08:10 +0000 |
| Subject: | note 87381 added to function.number-format | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-147566@lists.php.net to get a copy of this message | ||
Simple function to show money as only dollars if no cents, but will show 2 decimals if cents exist.
The 'cents' flag can force to never or always show 2 decimals
<?php
// formats money to a whole number or with 2 decimals; includes a dollar sign in front
function formatMoney($number, $cents = 1) { // cents: 0=never, 1=if needed, 2=always
if (is_numeric($number)) { // a number
if (!$number) { // zero
$money = ($cents == 2 ? '0.00' : '0'); // output zero
} else { // value
if (floor($number) == $number) { // whole number
$money = number_format($number, ($cents == 2 ? 2 : 0)); // format
} else { // cents
$money = number_format(round($number, 2), ($cents == 0 ? 0 : 2)); // format
} // integer or decimal
} // value
return '$'.$money;
} // numeric
} // formatMoney
$a = array(1, 1234, 1.5, 1.234, 2.345, 2.001, 2.100, '1.000', '1.2345',
'12345', 0, '0.00');
// show cents if needed ($cents=1)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 1));
1 = $1
1234 = $1,234
1.5 = $1.50
1.234 = $1.23
2.345 = $2.35
2.001 = $2.00
2.1 = $2.10
1.000 = $1
1.2345 = $1.23
12345 = $12,345
0 = $0
0.00 = $0
// never show cents ($cents=0)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 0));
1 = $1
1234 = $1,234
1.5 = $2
1.234 = $1
2.345 = $2
2.001 = $2
2.1 = $2
1.000 = $1
1.2345 = $1
12345 = $12,345
0 = $0
0.00 = $0
// always show cents ($cents=2)
foreach ($a as $b) echo ('<br />'.$b.' = '.formatMoney($b, 2));
1 = $1.00
1234 = $1,234.00
1.5 = $1.50
1.234 = $1.23
2.345 = $2.35
2.001 = $2.00
2.1 = $2.10
1.000 = $1.00
1.2345 = $1.23
12345 = $12,345.00
0 = $0.00
0.00 = $0.00
?>
Cheers :)
And remember to always contribute custom functions if they might be useful to the rest of us or
future versions of the php language.
----
Server IP: 69.147.83.197
Probable Submitter: 76.245.125.170
----
Manual Page -- http://www.php.net/manual/en/function.number-format.php
Edit -- https://master.php.net/note/edit/87381
Del: integrated -- https://master.php.net/note/delete/87381/integrated
Del: useless -- https://master.php.net/note/delete/87381/useless
Del: bad code -- https://master.php.net/note/delete/87381/bad+code
Del: spam -- https://master.php.net/note/delete/87381/spam
Del: non-english -- https://master.php.net/note/delete/87381/non-english
Del: in docs -- https://master.php.net/note/delete/87381/in+docs
Del: other reasons-- https://master.php.net/note/delete/87381
Reject -- https://master.php.net/note/reject/87381
Search -- https://master.php.net/manage/user-notes.php