PHP Currency Formatting

I currently have a fairly simple PHP script that displays a few columns of data, and paginates all the entries. I am trying to get my DECIMAL field (Cost) to display like $123,000,000 with the commas and currency symbols.

I am aware of the PHP currency formatting string, I just don’t know how to implement it in my script. My full script is below.

Thanks for your help ahead of time!
[php]

<?php //DATABASE SETTINGS $config['host'] = "localhost"; $config['user'] = ""; $config['pass'] = ""; $config['database'] = ""; $config['table'] = ""; $config['nicefields'] = true; //true or false | "Field Name" or "field_name" $config['perpage'] = 60; $config['showpagenumbers'] = true; //true or false $config['showprevnext'] = true; //true or false /******************************************/ //SHOULDN'T HAVE TO TOUCH ANYTHING BELOW... //except maybe the html echos for pagination and arrow image file near end of file. include 'scripts/Pagination.php'; $Pagination = new Pagination(); //CONNECT mysql_connect($config['host'], $config['user'], $config['pass']); mysql_select_db($config['database']); //get total rows $totalrows = mysql_fetch_array(mysql_query("SELECT count(*) as total FROM `".$config['table']."`")); //limit per page, what is current page, define first record for page $limit = $config['perpage']; if(isset($_GET['page']) && is_numeric(trim($_GET['page']))){$page = mysql_real_escape_string($_GET['page']);}else{$page = 1;} $startrow = $Pagination->getStartRow($page,$limit); //create page links if($config['showpagenumbers'] == true){ $pagination_links = $Pagination->showPageNumbers($totalrows['total'],$page,$limit); }else{$pagination_links=null;} if($config['showprevnext'] == true){ $prev_link = $Pagination->showPrev($totalrows['total'],$page,$limit); $next_link = $Pagination->showNext($totalrows['total'],$page,$limit); }else{$prev_link=null;$next_link=null;} //IF ORDERBY NOT SET, SET DEFAULT if(!isset($_GET['orderby']) OR trim($_GET['orderby']) == ""){ //GET FIRST FIELD IN TABLE TO BE DEFAULT SORT $sql = "SELECT length FROM `".$config['table']."` LIMIT 1"; $result = mysql_query($sql) or die(mysql_error()); $array = mysql_fetch_assoc($result); //first field $i = 0; foreach($array as $key=>$value){ if($i > 0){break;}else{ $orderby=$key;} $i++; } //default sort $sort="ASC"; }else{ $orderby=mysql_real_escape_string($_GET['orderby']); } //IF SORT NOT SET OR VALID, SET DEFAULT if(!isset($_GET['sort']) OR ($_GET['sort'] != "ASC" AND $_GET['sort'] != "DESC")){ //default sort $sort="desc"; }else{ $sort=mysql_real_escape_string($_GET['sort']); } //GET DATA $sql = "SELECT length,link_to_broker_listing,namelink,year,GD,cost,advertisers,advertiserlink FROM `".$config['table']."` ORDER BY $orderby $sort LIMIT $startrow,$limit"; $result = mysql_query($sql) or die(mysql_error()); //START TABLE AND TABLE HEADER echo "\n"; $array = mysql_fetch_assoc($result); $i = 0; foreach ($array as $key=>$value) { if($config['nicefields']){ $field = str_replace("_"," ",$key); $field = ucwords($field); } $field = columnSortArrows($key,$field,$orderby,$sort); if($i !=2 && $i!=7) echo "\n"; $i = $i +1; } echo "\n"; //reset result pointer mysql_data_seek($result,0); //start first row style $tr_class = "class='odd'"; //LOOP TABLE ROWS while($row = mysql_fetch_assoc($result)){ echo "\n"; $i=0; //used to count fields... foreach ($row as $field=>$value) { if($i==1){ $namelink=$value; } elseif($i==0){ echo ""; } elseif($i==2){ echo ""; } elseif($i==3){ echo ""; } elseif($i==4){ echo ""; } elseif($i==5){ echo ""; } elseif($i==6){ $advertiserlink=$value; } elseif($i==7){ echo ""; } $i=$i+1; } echo "\n"; //switch row style if($tr_class == "class='odd'"){ $tr_class = "class='even'"; }else{ $tr_class = "class='odd'"; } } //END TABLE echo "
" . $field . "
$value " . $namelink . " $value  $value $value " . $advertiserlink . "
\n"; if(!($prev_link==null && $next_link==null && $pagination_links==null)){ echo '
'."\n"; echo $prev_link; echo $pagination_links; echo $next_link; echo "
\n"; } /*FUNCTIONS*/ function columnSortArrows($field,$text,$currentfield=null,$currentsort=null){ //defaults all field links to SORT ASC //if field link is current ORDERBY then make arrow and opposite current SORT $sortquery = "sort=ASC"; $orderquery = "orderby=".$field; if($currentsort == "ASC"){ $sortquery = "sort=DESC"; } if($currentsort == "DESC"){ $sortquery = "sort=ASC"; } if($currentfield == $field){ $orderquery = "orderby=".$field; }else{ $sortarrow = null; } return ''.$text.' '. $sortarrow; } ?>[/php]

Oh, I forgot.

The script is working here: http://dev.aiowebservices.com/pnwb/masterinventory.php

[php]{
if($i==1){ $namelink=$value; }
elseif($i==0){ echo "

$value "; }
elseif($i==2){ echo “” . $namelink . “”; }
elseif($i==3){ echo " $value "; }
elseif($i==4){ echo "  $value "; }
elseif($i==5){ echo " $value "; }
// if $i is 5(what I’ve come to collect as where you’re printing your dollars… in the if statement you’ll need)
//setlocale(LC_MONETARY, ‘en_US’); or you could set this before the loop if everything will be in $ otherwise
// change it based on another clause.
//echo money_format(’%(#10n’, $value); --may require a little tweaking as I copied this from php.net never actually used it
elseif($i==6){ $advertiserlink=$value; }
elseif($i==7){ echo “<td width=‘100’ align=‘left’ style='padding-right: 18px;padding-left: 18px;'class=‘invfont2’>” . $advertiserlink . “”; }
$i=$i+1; // just a note $i++; would work just the same.
}[/php]

I tried it a couple of ways in the code and ran into some problems.

Any other more specific help would be appreciated.

try changing just the elseif($i==5) line to this:
[php]
elseif($i==5) { setlocale(LC_MONETARY, ‘en_US’); $value = money_format(’%(#10n’, $value); echo “

$value”; }
[/php]
Let me know if it works

Awesome! Thanks!

http://dev.aiowebservices.com/pnwb/masterinventory.php

The next thing would be to remove the space between the $ and the currency. I tried removing it a few times by cutting spaces out in the code but it still is there. Any ideas?

Well, in your code: 18px;’> $value ";
You have spaces before and after the value… Hmmmm, I bet if you remove the leading space…

Try that!

I took out all the spaces:

[php]elseif($i==5){setlocale(LC_MONETARY,‘en_US’);$value=money_format(’%(#10n’,$value);echo"

$value"; }[/php]

and it still has the same space issue. I checked the source code and it is showing it such as :

$ 9,075,000.00 (with all the white spaces)

Not sure why it is doing that

Well, there are two ways I found that can fix this.

  1. use sprintf… Something like this: (Remove the number formating line and use this)

    echo “$” . sprintf("%01.2f", $cost); which is set to 2 decimal points. Have not tested…

  2. user english_number_format function in PHP (remove the number formating line and use this)

    echo “$” . number_format ($cost, 2, ‘.’ , ‘,’ );

What #2 is basically formatting with 2 decimals, using period for decimal and comma for thousands.

Either should work, but, I would use #2. the money formatting way puts a $ into the string. and a space by default. Using number formatting, you have to add the $ in place… Should work best!

The only problem with manually putting the “$” into the code, is what to do if there is no cost (some of the links may not have a cost to go with them). I don’t want it to display just a “$” if the cost field is meant to be blank.

Is there an easy fix for that?

Thanks

If there is no cost you can check if the value is null and then make it 000 => $0.00–I think this would be most asthetically appeasing as if your scrolling through a table and have periodic blank fields it just looks like something is missng… or you can check if null and tell the script not to include the $

Notaloafer, you are formatting your dollars with a with of 10 so, the $ stays at the left. I think you should change to one of the other formats I gave you. Try them… Good luck…

One thing, money_format doesn’t work on a windows based host and as far as i know, there’s no way around it. and SET doesn’t always work, it depends on if the host allows it or not. I ran into that problem with an old project.

Richei,
So, the money_format doesn’t work on Windows systems? I have not tried it, but, so that would mean you could use it online if it was a Linux system, but, not locally if you test on your local Windows.

Hmmm! You would think that would be something that PHP would fix! Interesting as I am setting up a local Windows server with Wamp soon and I have several project that use money_format! Thanks for that heads-up!

Sorry for the delayed response - been busy with other projects.

Thanks for the tip on number_format. It is displaying correctly now: http://dev.aiowebservices.com/pnwb/masterinventory.php?page=1&orderby=cost&sort=ASC

However, I set a “NULL” value for cost for the first listing, and it is showing as $0.00 . What is the best way to go about fixing that? I read some of the replies, but am not sure how to proceed. I just want it to display nothing at all - no $ or 0.00 if there is no value for the field.

Thanks again everyone.

Here is the current code as it sits now - forgot to re-post that.

[php]

<?php //DATABASE SETTINGS $config['host'] = ""; $config['user'] = ""; $config['pass'] = ""; $config['database'] = ""; $config['table'] = ""; $config['nicefields'] = true; //true or false | "Field Name" or "field_name" $config['perpage'] = 60; $config['showpagenumbers'] = true; //true or false $config['showprevnext'] = true; //true or false /******************************************/ //SHOULDN'T HAVE TO TOUCH ANYTHING BELOW... //except maybe the html echos for pagination and arrow image file near end of file. include 'scripts/Pagination.php'; $Pagination = new Pagination(); //CONNECT mysql_connect($config['host'], $config['user'], $config['pass']); mysql_select_db($config['database']); //get total rows $totalrows = mysql_fetch_array(mysql_query("SELECT count(*) as total FROM `".$config['table']."`")); //limit per page, what is current page, define first record for page $limit = $config['perpage']; if(isset($_GET['page']) && is_numeric(trim($_GET['page']))){$page = mysql_real_escape_string($_GET['page']);}else{$page = 1;} $startrow = $Pagination->getStartRow($page,$limit); //create page links if($config['showpagenumbers'] == true){ $pagination_links = $Pagination->showPageNumbers($totalrows['total'],$page,$limit); }else{$pagination_links=null;} if($config['showprevnext'] == true){ $prev_link = $Pagination->showPrev($totalrows['total'],$page,$limit); $next_link = $Pagination->showNext($totalrows['total'],$page,$limit); }else{$prev_link=null;$next_link=null;} //IF ORDERBY NOT SET, SET DEFAULT if(!isset($_GET['orderby']) OR trim($_GET['orderby']) == ""){ //GET FIRST FIELD IN TABLE TO BE DEFAULT SORT $sql = "SELECT length FROM `".$config['table']."` LIMIT 1"; $result = mysql_query($sql) or die(mysql_error()); $array = mysql_fetch_assoc($result); //first field $i = 0; foreach($array as $key=>$value){ if($i > 0){break;}else{ $orderby=$key;} $i++; } //default sort $sort="ASC"; }else{ $orderby=mysql_real_escape_string($_GET['orderby']); } //IF SORT NOT SET OR VALID, SET DEFAULT if(!isset($_GET['sort']) OR ($_GET['sort'] != "ASC" AND $_GET['sort'] != "DESC")){ //default sort $sort="desc"; }else{ $sort=mysql_real_escape_string($_GET['sort']); } //GET DATA $sql = "SELECT length,link_to_broker_listing,namelink,year,GD,cost,advertisers,advertiserlink FROM `".$config['table']."` ORDER BY $orderby $sort LIMIT $startrow,$limit"; $result = mysql_query($sql) or die(mysql_error()); //START TABLE AND TABLE HEADER echo "\n"; $array = mysql_fetch_assoc($result); $i = 0; foreach ($array as $key=>$value) { if($config['nicefields']){ $field = str_replace("_"," ",$key); $field = ucwords($field); } $field = columnSortArrows($key,$field,$orderby,$sort); if($i !=2 && $i!=7) echo "\n"; $i = $i +1; } echo "\n"; //reset result pointer mysql_data_seek($result,0); //start first row style $tr_class = "class='odd'"; //LOOP TABLE ROWS while($row = mysql_fetch_assoc($result)){ echo "\n"; $i=0; //used to count fields... foreach ($row as $field=>$value) { if($i==1){ $namelink=$value; } elseif($i==0){ echo ""; } elseif($i==2){ echo ""; } elseif($i==3){ echo ""; } elseif($i==4){ echo ""; } elseif($i==5){ echo ""; } #elseif($i==5){setlocale(LC_MONETARY,'en_US');$value=money_format('%(#10n',$value);echo""; } elseif($i==6){ $advertiserlink=$value; } elseif($i==7){ echo ""; } $i=$i+1; } echo "\n"; //switch row style if($tr_class == "class='odd'"){ $tr_class = "class='even'"; }else{ $tr_class = "class='odd'"; } } //END TABLE echo "
" . $field . "
$value " . $namelink . " $value $value $" . number_format ($value, 2, '.' , ',' );"$value" . $advertiserlink . "
\n"; if(!($prev_link==null && $next_link==null && $pagination_links==null)){ echo '
'."\n"; echo $prev_link; echo $pagination_links; echo $next_link; echo "
\n"; } /*FUNCTIONS*/ function columnSortArrows($field,$text,$currentfield=null,$currentsort=null){ //defaults all field links to SORT ASC //if field link is current ORDERBY then make arrow and opposite current SORT $sortquery = "sort=ASC"; $orderquery = "orderby=".$field; if($currentsort == "ASC"){ $sortquery = "sort=DESC"; } if($currentsort == "DESC"){ $sortquery = "sort=ASC"; } if($currentfield == $field){ $orderquery = "orderby=".$field; }else{ $sortarrow = null; } return ''.$text.' '. $sortarrow; } ?>
						</td>
					</tr>
					<tr>
						<td height="20"></td>
					</tr>
				</table>				
			</td>
			<td width="180" valign="top" bgcolor="#ebeef3">
				<table width="180" cellpadding="0" cellspacing="0">
					<tr>
						<td height="131" align="center">
						</td>
					</tr>
					<tr>
						<td height="10"></td>
					</tr>
					<tr>
						<td class="navbarheader"></td>
					</tr>					
					<tr>
						<td height="10"></td>
					</tr>
					<tr>
						<td>
						

						</td>
					</tr>
					<tr>
						<td height="10"></td>
					</tr>						
				</table>				
			</td>					
		</tr>		
	</table>
	</td>
</tr>
[/php]

So, it looks like the number_format function worked for you! Great!

Had to page back to see your next question…

Just do an IF clause, basically something like:
if(cost>0)
{
//display your number_formatted cost…
}

Then, if it is zero, it does nothing… Good luck…

Where you’re looking at the cost, do what ernie said, just instead of doing nothing, do an else and have it just display a space or a hypen

I tried a couple of ways of inserting my new IF statement directly in-line with my elseif statement for that particular line and had some parsing errors come up. Where is the best place to put that to avoid the parsing errors?

Sponsor our Newsletter | Privacy Policy | Terms of Service