Page 1 of 1

Comma seperated money values?

Posted: Thu Jan 14, 2010 3:12 pm
by ShadowIce
Hi all, how can I make it so that no matter HOW many numbers are in this string, it seperates them correctly w/ a comma, so it displays the correct amount of money?

code:

Code: Select all

<?php
$Total = "012345678901234567890000";
echo "Your total: <b><u>$".$Total."</u></b><br>\n";
?>
Also, how can I make it so that if it's an even amount, such as: $100, or $101, it adds a ".00" to the end? or if its a number under 9 cents, it adds a ".0", or if it's 90 cents, it adds a "0" to the end of it, so: "$1,000,000,000,000,000.01", "$109,000,000,000,000,000.09", "$109,000,000,000,000,000.90"

So: $100.00

Thanks!

ShadowIce~

Re: Comma seperated money values?

Posted: Thu Jan 14, 2010 3:49 pm
by AbraCadaver
number_format() or money_format()

Re: Comma seperated money values?

Posted: Thu Jan 14, 2010 4:27 pm
by ShadowIce
For anyone else looking for this type of code, here it is, it FIXES problems in the regular number_format() code:

Code: Select all

<?php
function wims_currency($number) {
   if ($number < 0) {
     $print_number = "($" . str_replace('-', '', number_format ($number, 2, ".", ",")) . ")";
    } else {
     $print_number = "$" .  number_format ($number, 2, ".", ",") ;
   }
   return $print_number;
}
 
$Total = "1234567890987654321234567890987654321234567890.9";
$number = $Total;
$pur_item_total = $number;
$pur_po_total =  ($pur_po_total + $pur_item_total);
$print_pur_po_total = wims_currency($pur_po_total);
echo $print_pur_po_total."<br>\n";
 
?>
ENJOY! And thanks again, Abra! =D

PS. If you have a number, and u want a double-digit decimal after it (like: $1234,56.78), u simply make total look like this: " $Total = "123456.78"; " Also, if u have only ONE decimal on total, it will add a ".0" to the end of it. it ALSO adds the "$" before the number, so u dont have to put that either!

In other words: IT'S PERFECT! ENJOY! =D

ShadowIce~

Re: Comma seperated money values?

Posted: Thu Jan 14, 2010 4:35 pm
by AbraCadaver
What problems in number_format()??? If you give it a negative number it formats it and gives you a negative number back. If at anytime you want to make sure you have a positive number then use abs().

Code: Select all

$print_number = "$" . number_format(abs($number), 2);
if ($number < 0) {
     $print_number = "($print_number)";
}

Re: Comma seperated money values?

Posted: Thu Jan 14, 2010 4:40 pm
by ShadowIce
nvm, lol. alls im saying is its PERFECT. i tested it in ALL ways :)

Re: Comma seperated money values?

Posted: Thu Jan 14, 2010 4:44 pm
by AbraCadaver
Sorry, I failed to see that you added ( ) around the negative number. :-) Still, not a problem with number_format().