Solved

Round a number to 2 decimal points in php

Posted on 2014-12-19
25
208 Views
Last Modified: 2014-12-19
I'm stumped on why this isn't working. $taxes is a whole number for annual taxes, but I need to divide it so it's shown for monthly. The division works fine, but has too many digits rather than just 2 after the decimal point. Like this: 8.658572115012E-48

When I try using 'round' it sets the number to 0 instead of 8.66 as you would expect.

I tested the variable to be sure it's a number and not a string and it tested true to be a number.

		$taxes = $taxes / 12; 
		$taxes = round($taxes, 2);

Open in new window


Anyone have an idea why it's not working or have another method to try?
0
Comment
Question by:Dzynit
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 12
  • 4
  • 3
  • +3
25 Comments
 
LVL 19

Expert Comment

by:Greg Alexander
ID: 40509747
Have you tried number_fomat

$taxes = $taxes / 12; 
$taxes = number_format($taxes, 2);

Open in new window

0
 
LVL 14

Author Comment

by:Dzynit
ID: 40509756
Yeah, it gave 2 decimal points but still set it to 0.
ex: 0.00
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 40509807
What are the original numbers?
0
Major Incident Management Communications

Major incidents and IT service outages cost companies millions. Often the solution to minimizing damage is automated communication. Find out more in our Major Incident Management Communications infographic.

 
LVL 14

Author Comment

by:Dzynit
ID: 40509812
The one that results in 8.658572115012E-48 after division is 380.
0
 
LVL 14

Author Comment

by:Dzynit
ID: 40509815
Does the E- maybe have something to do with it? Maybe there's a better method for division?
0
 
LVL 84

Expert Comment

by:ozo
ID: 40509890
8.658572115012E-48 rounded to two decimal places is 0.00
0
 
LVL 14

Author Comment

by:Dzynit
ID: 40509895
Yeah, something isn't working right with the division. 380 is $380 per year. I need to show that as monthly though and using my calculator, monthly would be $31.67.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40509912
$taxes=380;
   echo $taxes,"\n";
   $taxes = $taxes / 12;
   echo $taxes,"\n";
   $taxes = round($taxes, 2);
   echo $taxes,"\n";
prints
380
31.666666666667
31.67
0
 
LVL 14

Author Comment

by:Dzynit
ID: 40509944
The only way it works correctly is if I manually set $taxes to 380, but I can't do that. It has to be assigned per home coming from the database.

I even tried:
$taxes = (double)$taxes/12;

Open in new window


But it's still the wrong calculation.
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 40509980
What happens when you do var_dump($taxes)
0
 
LVL 37

Expert Comment

by:Neil Russell
ID: 40509993
$taxed = (double)$taxes;
$monthly =round(  $taxed / 12.0 );

 

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
ID: 40510001
What is the value of $taxes per home coming from the database, and how are you assigning that value?
0
 
LVL 14

Author Comment

by:Dzynit
ID: 40510010
I can't try that because after all the php programming, it displays xml feed. Try to display any php will just show an error.
0
 
LVL 14

Author Comment

by:Dzynit
ID: 40510016
The taxes variable tests true for being a number, but all I can find searching on the way it's acting is that it's still being treated like a string.
I got the ok to just omit it from the feed, but it really bugs me as to why it's not working right.
0
 
LVL 37

Expert Comment

by:Neil Russell
ID: 40510048
Did you try the code I posted above?
0
 
LVL 84

Expert Comment

by:ozo
ID: 40510049
What is the value of the number, and what string is it being treated like?
0
 
LVL 14

Author Comment

by:Dzynit
ID: 40510056
Yes, that works if I assign the number directly to it in the php. But when the number is assigned coming from the database it's not calculating right.
0
 
LVL 37

Expert Comment

by:Neil Russell
ID: 40510170
can you paste code showing how you read from the database and assign to the variable $taxes please.
0
 
LVL 14

Author Comment

by:Dzynit
ID: 40510238
<?php
// Start XML file, create parent node
$doc = new DOMDocument("1.0");
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$node = $doc->createElement("Listings");
$parnode = $doc->appendChild($node); 

mysql_connect("localhost", "jandmhomes_jandm", "---------") or die(mysql_error());
mysql_select_db("jandmhomes_jandm") or die(mysql_error());

$propertyresult = mysql_query("SELECT * FROM wp_posts
 WHERE post_status NOT LIKE 'draft' AND 'post_status' NOT LIKE 'trash' AND post_type='property'") or die(mysql_error());

header("Content-type: text/xml");

while ($propertyid = mysql_fetch_array( $propertyresult )) {
//echo '<pre>'; print_r($propertyid); echo '</pre>';	
	$result = mysql_query("SELECT * FROM wp_postmeta
	 WHERE post_id='".$propertyid['ID']."'") or die(mysql_error());  
	
	// ID and creation date
	$id = $propertyid['ID'];
	$created_at = date("Y-m-d", strtotime($propertyid['post_date']));
	$name = $propertyid['post_title'];
	$description = $propertyid['post_content'];
	$description = substr($description, 0, 65000);
	$description = utf8_encode(htmlspecialchars($description, ENT_QUOTES));

	while ($row = mysql_fetch_array( $result )) {
		
		//echo $row['meta_key'].' - '.$row['meta_value'].'<br />';

		// ID - declared above

		// User
		// THIS IS WHERE THE AGENT ID # AND KEEY NEEDS CHANGED PER LOCATION XML FILE  AND ALSO BELOW ABOVE XML PRINTING
		if($row['meta_key'] == 'wpp_agents') { 
			if ($row['meta_value'] == '18') { 
				$getuserinfo = mysql_query("SELECT * FROM wp_users
				 WHERE ID='".$row['meta_value']."'") or die(mysql_error()); 
				$userinfo = mysql_fetch_array( $getuserinfo );
				$first_name = $userinfo['display_name'];
				$email = $userinfo['user_email'];
				$getuserphone = mysql_query("SELECT * FROM wp_usermeta WHERE user_id = ".$row['meta_value']." AND meta_key LIKE 'phone_number'") or die(mysql_error());
				$userphone = mysql_fetch_array( $getuserphone );
				$phone = $userphone['meta_value'];
				$phone = str_replace('(', '', $phone); $phone = str_replace(') ', '-', $phone);	$phone = str_replace(')', '-', $phone);
				$website = 'http://www.jandmhomes.com';
				$whichlocation = '18';
				$selleracctkey = '143617305';
			}
		} 
		
		// Name - declared above

		// Address
		if($row['meta_key'] == 'city') { $city = $row['meta_value']; }
			if ($city == '') {
				$city = $first_name;
			}
		if($row['meta_key'] == 'state_only') { $state = $row['meta_value']; }
			if ($state == '') {
				if ($city == "Woodland") {
					$state = "WA";
				} else {
					$state = "OR";
				}
			}
		if($row['meta_key'] == 'zip_code') { $postal_code = $row['meta_value']; }
		$country = 'USA';

		// Type
		$type = 'MobileHome';

		// Priority
		if($row['meta_key'] == 'featured' && $row['meta_value'] == 'true') { $priority = 'featured'; }

		// Sale Type
		$sale_type = 'sale';

		// Price
		if($row['meta_key'] == 'price') { $price1 = $row['meta_value']; }
		if($row['meta_key'] == 'price_as_shown') { $price2 = $row['meta_value']; }
		if($row['meta_key'] == 'blowout_price') { $price3 = $row['meta_value']; }
		if ($price3 != '') { $price = $price3; }
		if ($price2 != '' && $price == '') { $price = $price2; }
		if ($price1 != '' && $price == '') { $price = $price1; }

		// Rental price
		if($row['meta_key'] == 'space_rent') { $lotrent = $row['meta_value']; }
		
		// Description - declared above

		// Created at - declared above
		
		// Photos - set below

		// Details
		if($row['meta_key'] == 'property_type') { 
			if($row['meta_value'] == 'new_home') { $is_new = 'true'; } else { $is_new = 'false'; }
		}
		if($row['meta_key'] == 'year_built') { $year = $row['meta_value']; }
		if($row['meta_key'] == 'manufacturer') { $manufacturer = $row['meta_value']; }
		if($row['meta_key'] == 'bedrooms') { $num_beds = $row['meta_value']; }
		if($row['meta_key'] == 'bathrooms') { $num_baths = $row['meta_value']; }
		if($row['meta_key'] == 'size') { 
			$size = $row['meta_value'];
			$size = explode('x',strtolower(str_replace(' ', '', $size)));
			$width = $size[0];
			$length = $size[1];
		}
		if($row['meta_key'] == 'square_feet') { $home_sqft = $row['meta_value']; }
		if($row['meta_key'] == 'bathrooms') { $num_baths = $row['meta_value']; }

		// Add reference # to description
		if($row['meta_key'] == 'our_reference_') { $ref = $row['meta_value']; }
			if ($is_new == 'true') {
				$ref = $manufacturer;
			}

		// Set LocationType
		if($row['meta_key'] == 'new_home_display_model') { 
			$locationtypeanswer = $row['meta_value'];
			if ($locationtypeanswer == 'Yes') { $locationtype = 'DealerLot'; }
		}	
		if($row['meta_key'] == 'location') { 
			$locationtypeanswer = $row['meta_value'];
			if ($locationtypeanswer == 'A Used Home To Be Moved') { $locationtype = 'Move'; }
		}	
		if($row['meta_key'] == 'on_lot') { 
			$locationtypeanswer = $row['meta_value'];
			if ($locationtypeanswer == 'Yes') { $locationtype = 'Community'; }
		}			
		
		// Set square feet
		if($row['meta_key'] == 'square_feet') { $sqft = $row['meta_value']; }

		// Set home features
		if($row['meta_key'] == 'garage') { $garage = $row['meta_value']; }
		if($row['meta_key'] == 'car_port') { $carport = $row['meta_value']; }
		if($row['meta_key'] == 'airconditioning') { $airconditioning = $row['meta_value']; }
		if($row['meta_key'] == 'fireplace') { $fireplace = $row['meta_value']; }
		if($row['meta_key'] == 'storageshed') { $storageshed = $row['meta_value']; }
		if($row['meta_key'] == 'deck') { $deck = $row['meta_value']; }
		if($row['meta_key'] == 'corner_pantry') { $pantry = $row['meta_value']; }
		if($row['meta_key'] == 'garden_tub') { $gardentub = $row['meta_value']; }	
		if($row['meta_key'] == 'disposal') { $disposal = $row['meta_value']; }	
		if($row['meta_key'] == 'refrigerator') { $refrigerator = $row['meta_value']; }	
		if($row['meta_key'] == 'microwave') { $microwave = $row['meta_value']; }
		if($row['meta_key'] == 'gas_range') { $oven = $row['meta_value']; }
		if($row['meta_key'] == 'dishwasher') { $dishwasher = $row['meta_value']; }
		if($row['meta_key'] == 'washerdryer') { $washerdryer = $row['meta_value']; }

		// Set Property Tax
		if($row['meta_key'] == 'annual_property_tax') { $taxes = $row['meta_value']; }
		//$taxes = 380;
		$taxes = (double)$taxes/12;
		
		// Set search result text
		if($row['meta_key'] == 'short_description_for_in_site_search') { $searchtxt = $row['meta_value']; }
		$searchtxt = substr($searchtxt, 0, 80);
		$searchtxt = utf8_encode(htmlspecialchars($searchtxt, ENT_QUOTES));		
		
		// Set if sale pending
		if($row['meta_key'] == 'status') { $salepending = $row['meta_value']; }
		if($salepending == 'Pending') { $salepending = 'Yes'; } else { $salepending = 'No'; }
	}
	

if ($whichlocation == '18') {		
$name = $name.' ('.$ref.')';
//$description = $description.' Please reference '.$ref.' when contacting about this home.';


	// PUT TOGETHER XML
	$node = $doc->createElement("Listing");
	$newnode = $parnode->appendChild($node);

	$node_id = $doc->createElement("SellerID", $id);
	$node->appendChild($node_id);

	$node_price = $doc->createElement("AskingPrice", $price);
	$node->appendChild($node_price);
	
	$node_description = $doc->createElement("Description", $description);
	$node->appendChild($node_description);

	$node_locationtype = $doc->createElement("LocationType", $locationtype);
	$node->appendChild($node_locationtype);	

	$node_address = $doc->createElement("Address1");
	$node->appendChild($node_address);
	$node_address_city = $doc->createElement("City", $city);
	$node->appendChild($node_address_city);
	$node_address_state = $doc->createElement("State", $state);
	$node->appendChild($node_address_state);
	$node_address_postal_code = $doc->createElement("Zip9", $postal_code);
	$node->appendChild($node_address_postal_code);

	$node_detail_manufacturer = $doc->createElement("Make", $manufacturer);
	$node->appendChild($node_detail_manufacturer);
	$node_detail_year = $doc->createElement("Year", $year);	
	$node->appendChild($node_detail_year);

	$node_detail_width = $doc->createElement("Width1", $width);
	$node->appendChild($node_detail_width);
	$node_detail_length = $doc->createElement("Length1", $length);
	$node->appendChild($node_detail_length);
	$node_detail_sqft = $doc->createElement("SquareFeet", $sqft);
	$node->appendChild($node_detail_sqft);
		
	$node_detail_num_beds = $doc->createElement("Bedrooms", $num_beds);
	$node->appendChild($node_detail_num_beds);
	$node_detail_num_baths = $doc->createElement("Bathrooms", $num_baths);
	$node->appendChild($node_detail_num_baths);

	$node_detail_garage = $doc->createElement("Garage", $garage);
	$node->appendChild($node_detail_garage);
	$node_detail_carport = $doc->createElement("Carport", $carport);
	$node->appendChild($node_detail_carport);
	$node_detail_ac = $doc->createElement("CentralAir", $airconditioning);
	$node->appendChild($node_detail_ac);
	$node_detail_fireplace = $doc->createElement("Fireplace", $fireplace);
	$node->appendChild($node_detail_fireplace);
	$node_detail_storageshed = $doc->createElement("StorageShed", $storageshed);
	$node->appendChild($node_detail_storageshed);
	$node_detail_deck = $doc->createElement("Deck", $deck);
	$node->appendChild($node_detail_deck);
	$node_detail_pantry = $doc->createElement("Pantry", $pantry);
	$node->appendChild($node_detail_pantry);
	$node_detail_gardentub = $doc->createElement("GardenTub", $gardentub);
	$node->appendChild($node_detail_gardentub);
	$node_detail_disposal = $doc->createElement("GarbageDisposal", $disposal);
	$node->appendChild($node_detail_disposal);
	$node_detail_refrigerator = $doc->createElement("Refrigerator", $refrigerator);
	$node->appendChild($node_detail_refrigerator);
	$node_detail_microwave = $doc->createElement("Microwave", $microwave);
	$node->appendChild($node_detail_microwave);
	$node_detail_oven = $doc->createElement("Oven", $oven);
	$node->appendChild($node_detail_oven);
	$node_detail_dishwasher = $doc->createElement("Dishwasher", $dishwasher);
	$node->appendChild($node_detail_dishwasher);
	$node_detail_washer = $doc->createElement("ClothesWasher", $washerdryer);
	$node->appendChild($node_detail_washer);
	$node_detail_dryer = $doc->createElement("ClothesDryer", $washerdryer);
	$node->appendChild($node_detail_dryer);											

	$node_lotrent = $doc->createElement("LotRent", $lotrent);
	$node->appendChild($node_lotrent);

	$node_taxes = $doc->createElement("Taxes", $taxes);
	$node->appendChild($node_taxes);

	$node_searchtxt = $doc->createElement("SearchResultsText", $searchtxt);
	$node->appendChild($node_searchtxt);

	$node_sellerwebsite = $doc->createElement("SellerWebsite", "http://www.jandmhomes.com/");
	$node->appendChild($node_sellerwebsite);
	
	$node_selleracctkey = $doc->createElement("SellerAccountKey", $selleracctkey);
	$node->appendChild($node_selleracctkey);	

	$node_user_first_name = $doc->createElement("SellerContactName", $first_name);
	$node->appendChild($node_user_first_name);
	$node_user_co_name = $doc->createElement("SellerCompanyName", "J&amp;M Homes");
	$node->appendChild($node_user_co_name);		
	$node_user_phone = $doc->createElement("SellerPhone", $phone);
	$node->appendChild($node_user_phone);										
	$node_user_email = $doc->createElement("SellerEmail", $email);
	$node->appendChild($node_user_email);

	$node_viewtype = $doc->createElement("ViewType", "Standard");
	$node->appendChild($node_viewtype);

	$node_salepending = $doc->createElement("SalePending", $salepending);
	$node->appendChild($node_salepending);
	
			// Photos
			$getphotos = mysql_query("SELECT * FROM wp_postmeta WHERE post_id = ".$id." AND meta_key LIKE 'slideshow_images'") or die(mysql_error());
			$photos = mysql_fetch_array( $getphotos );
			$photoids = unserialize($photos['meta_value']);
			$c = 0;
			foreach ((array)$photoids as $eachphoto) {
				$photoinfo = mysql_query("SELECT * FROM wp_posts WHERE id = '".$eachphoto."'") or die(mysql_error());
				$photo = mysql_fetch_array( $photoinfo );
				$photoaltinfo = mysql_query("SELECT * FROM wp_postmeta WHERE post_id = '".$eachphoto."' AND meta_key LIKE '_wp_attachment_image_alt'") or die(mysql_error());
				$photoalt = mysql_fetch_array( $photoaltinfo );
				if ($photoalt['meta_value'] == '') { $photoalt['meta_value'] = $name; }
				$photourl = $photo['guid'];
				$phototitle = $photoalt['meta_value'];
				$node_photourl = $doc->createElement("PhotoURL", $photourl);
				$node->appendChild($node_photourl);

				$c++;
				if ($c == 20) { break; }
			}
}
}

echo $doc->saveXML();


// NOTES:
// Set character limit on description
// Put ref # on title if Jim and Scott agree

//$myFile = "jandm.xml";
//$fh = fopen($myFile, 'w') or die("can't open file");
//$stringData = $doc->saveXML();
//fwrite($fh, $stringData);
//fclose($fh);

?>

Open in new window

0
 
LVL 14

Author Comment

by:Dzynit
ID: 40510239
0
 
LVL 14

Author Comment

by:Dzynit
ID: 40510243
To moderators, I forgot to x out the user/pw on the db connect lines. I'm unable to edit that comment now - could you do that for me?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40510350
Without knowing the real number, and it's strange why you would be getting 0.00 amend your code as such
		if($row['meta_key'] == 'annual_property_tax') { $taxes = $row['meta_value']; }
		//$taxes = 380;
		$taxes = format_number(ceil($taxes * 100)/100,2);

Open in new window

0
 
LVL 35

Accepted Solution

by:
gr8gonzo earned 500 total points
ID: 40510372
There's really only 2 sources of the problem here: Code or Data.

If you set the data manually to 380 and it works, then that means that either the code is 100% correct and the original data in the database is incorrect, OR the original data is being screwed up by code. That is really the only set of conclusions left.

First, I should note that your $taxes value is CONDITIONALLY initialized and handled:

// Set Property Tax
            if($row['meta_key'] == 'annual_property_tax') { $taxes = $row['meta_value']; }
            //$taxes = 380;
            $taxes = (double)$taxes/12;

This is just bad coding. Think about this - whenever you're in a loop where $row["meta_key"] is NOT annual_property_tax, then you are still running the code:

$taxes = (double)$taxes/12;
... and so on...

So let's say you have 5 records:

blah blah = something
blue blah = something else
annual_property_tax = 380
blee blah = another thing
blar blah = final thing

When you're looping through, the first 2 records will still execute the $taxes = (double)$taxes / 12; line, which is pretty pointless when the value hasn't been initialized yet, and it'll also throw warnings.

Then you hit the annual_property_tax record and it works once. Then it hits the next couple lines and gets divided up by 12, and then by 12 again.

So I would make certain your taxes code is all wrapped in one conditional block with the part that initializes the value. Example:

// Set Property Tax
            if($row['meta_key'] == 'annual_property_tax') { $taxes = (double)$row['meta_value'] / 12; }
0
 
LVL 14

Author Closing Comment

by:Dzynit
ID: 40510400
You nailed it - thank you so much and also thank you for the edit on the pw of the code!
This is what made it finally work:
            // Set Property Tax
            if($row['meta_key'] == 'annual_property_tax') { $taxes = (double)$row['meta_value'] / 12; }
            $taxes = (round($taxes,2));
0

Featured Post

Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When it comes to write a Context Sensitive Help (an online help that is obtained from a specific point in state of software to provide help with that state) ,  first we need to make the file that contains all topics, which are given exclusive IDs. …
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question