PHP - How Do I Roun To 2 Decimal Places
i am echoing out a value which is 1.2900
but i want it to echo out 1.29 how do i do this? cheers matt Similar TutorialsHi, I'm trying to force 2 decimal places with the following function but it 's not working. Any suggestions? Code: [Select] function ShippingCost() { $shippingCost = 4.00; number_format($shippingCost,2); return $shippingCost; } Bascially i add a couple numbers up and display the sum. sometimes the number is something like this: 234.237 i want it to display : 234.24 i realize its needs "round()" in it but i dont know how to use it.. any help? Hey, just wondering what would be the best way of adding .1 to a string. For example: Code: [Select] $newversion = $currentversion + '0.0.1'; $newversion is taken from a db, lets say for this example it is 0.2.1 This code simply outputs 0.2 Any ideas? Thanks =) Hi.. I encountered problem in rounding of numbers into two decimal places. here is my sample code: if($W4_STATUS == 1 AND $DEPENDENTS == 0 AND $TotEarn >= 7917 AND $TotEarn <= 12500) { $TAX = ($TotEarn - 7917); $TAX = (937.50 + ($TAX * .25)); $TAX = number_format($TAX, 2, '.', ''); } for example from this: $TAX = ($TotEarn - 7917); $TAX = (937.50 + ($TAX * .25)); the output is: 1417.615 using this: $TAX = number_format($TAX, 2, '.', ''); the output was : 1417.61 but it should be : 1417.62 Thank you Hi I am using Zen-Cart to which I have made significant changes. Two years ago I managed to change the Products Sort Order from Integer to Decimal(5,2) to store books such as 1, 1.5, 1.75, 2 etc. Regrettably we had a major server issue and I also lost the new coding. Having restored everything else whenever we enter a book series number such as 1.5 it only stores as 1. To date the zen-Cart forums have been unable to offer a solution so I am reaching out to see if anyone else can advise me of how to get this working again please.
Thanks in advance Owen
This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=311051.0 For every search, I get ZERO RESULTS, and I don't understand what I'm doing wrong. Code: [Select] <?php require('places_class.php'); $types = $_POST['type']; $location = $_POST['place']; $radius = $_POST['radius']; $gplaces = New GooglePlaces; $gplaces->SetLocation("$location"); $gplaces->SetRadius($radius); $gplaces->SetTypes("$types"); $results = $gplaces->Search(); print_r($results); ?> That's when the form is submitted, I checked the variables, and they are echoing out correctly. Then I thought I'd hard-code the values in, same results Code: [Select] <?php require('places_class.php'); $gplaces = New GooglePlaces; $gplaces->SetLocation("40.5267,81.4778"); $gplaces->SetRadius(50); $gplaces->SetTypes("food"); $results = $gplaces->Search(); print_r($results); ?> Here is the class Code: [Select] <?php class GooglePlaces { private $APIKey = ""; public $OutputType = "json"; //either json, xml or array public $Errors = array(); private $APIUrl = "https://maps.googleapis.com/maps/api/place"; private $APICallType = ""; private $IncludeDetails = false; //all calls private $Language = 'en'; //optional - https://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 //Search private $Location; //REQUIRED - This must be provided as a google.maps.LatLng object. private $Radius; //REQUIRED private $Types; //optional - separate tyep with pipe symbol http://code.google.com/apis/maps/documentation/places/supported_types.html private $Name; //optional //Search, Details, private $Sensor = 'false'; //REQUIRED - is $Location coming from a sensor? like GPS? //Details & Delete private $Reference; //Add private $Accuracy; public function Search() { $this->APICallType = "search"; return $this->APICall(); } public function Details() { $this->APICallType = "details"; return $this->APICall(); } public function Checkin() { $this->APICallType = "checkin-in"; return $this->APICall(); } public function Add() { $this->APICallType = "add"; return $this->APICall(); } public function Delete() { $this->APICallType = "delete"; return $this->APICall(); } public function SetLocation($Location) { $this->Location = $Location; } public function SetRadius($Radius) { $this->Radius = $Radius; } public function SetTypes($Types) { $this->Types = $Types; } public function SetLanguage($Language) { $this->Language = $Language; } public function SetName($Name) { $this->Name = $Name; } public function SetSensor($Sensor) { $this->Sensor = $Sensor; } public function SetReference($Reference) { $this->Reference = $Reference; } public function SetAccuracy($Accuracy) { $this->Accuracy = $Accuracy; } public function SetIncludeDetails($IncludeDetails) { $this->IncludeDetails = $IncludeDetails; } private function CheckForErrors() { if(empty($this->APICallType)) { $this->Errors[] = "API Call Type is required but is missing."; } if(empty($this->APIKey)) { $this->Errors[] = "API Key is is required but is missing."; } if(($this->OutputType!="json") && ($this->OutputType!="xml") && ($this->OutputType!="json")) { $this->Errors[] = "OutputType is required but is missing."; } } private function APICall() { $this->CheckForErrors(); if($this->APICallType=="add" || $this->APICallType=="delete") { $URLToPostTo = $this->APIUrl."/".$this->APICallType."/".$this->OutputType."?key=".$this->APIKey."&sensor=".$this->Sensor; if($this->APICallType=="add") { $LocationArray = explode(",", $this->Location); $lat = trim($LocationArray[0]); $lng = trim($LocationArray[1]); $paramstopost[location][lat] = $lat; $paramstopost[location][lng] = $lng; $paramstopost[accuracy] = $this->Accuracy; $paramstopost[name] = $this->Name; $paramstopost[types] = explode("|", $this->Types); $paramstopost[language] = $this->Language; } if($this->APICallType=="delete") { $paramstopost[reference] = $this->Reference; } $result = json_decode($this->CurlCall($URLToPostTo,json_encode($paramstopost))); $result->errors = $this->Errors; return $result; } if($this->APICallType=="search") { $URLparams = "location=".$this->Location."&radius=".$this->Radius."&types=".$this->Types."&language=".$this->Language."&name=".$this->Name."&sensor=".$this->Sensor; } if($this->APICallType=="details") { $URLparams = "reference=".$this->Reference."&language=".$this->Language."&sensor=".$this->Sensor; } if($this->APICallType=="check-in") { $URLparams = "reference=".$this->Reference."&language=".$this->Language."&sensor=".$this->Sensor; } $URLToCall = $this->APIUrl."/".$this->APICallType."/".$this->OutputType."?key=".$this->APIKey."&".$URLparams; $result = json_decode(file_get_contents($URLToCall),true); $result[errors] = $this->Errors; if($result[status]=="OK" && $this->APICallType=="details") { foreach($result[result][address_components] as $key=>$component) { if($component[types][0]=="street_number") { $address_street_number = $component[short_name]; } if($component[types][0]=="route") { $address_street_name = $component[short_name]; } if($component[types][0]=="locality") { $address_city = $component[short_name]; } if($component[types][0]=="administrative_area_level_1") { $address_state = $component[short_name]; } if($component[types][0]=="postal_code") { $address_postal_code = $component[short_name]; } } $result[result][address_fixed][street_number] = $address_street_number; $result[result][address_fixed][address_street_name] = $address_street_name; $result[result][address_fixed][address_city] = $address_city; $result[result][address_fixed][address_state] = $address_state; $result[result][address_fixed][address_postal_code] = $address_postal_code; } return $result; } private function CurlCall($url,$topost) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $topost); $body = curl_exec($ch); curl_close($ch); return $body; } } ?> And yes, I do have the correct API Key, I just took it out Can anybody see what the issue is? how do i make a leaderboard that is capable of handling equal scores from a particular result? we use following points allocations: winner: 5pts second: 3pts third: 2pts fourth: 1pt however, if 2nd and 3rd have tied scores, i would like to combine their point allocations together and divide by 2, i.e. (3+2)/2=2.5points each. initial query for competition ranking: $q_lastcomp = "SELECT p.p_id, p.p_surname, p.p_forename, p.p_handicap, r.r_id, rp.rp_score, rp.rp_handicap, (rp.rp_score-rp.rp_handicap) as net_score "; $q_lastcomp .= "FROM dan_roundplayed rp, dan_round r, dan_player p "; $q_lastcomp .= "WHERE r.r_id = rp.rp_rid "; $q_lastcomp .= "AND p.p_id = rp.rp_pid "; $q_lastcomp .= "AND r.r_id = 6 "; $q_lastcomp .= "ORDER BY net_score"; $r_lastcomp = mysql_query($q_lastcomp) or die(mysql_error()); i then loop through this resultset in this order (top down), and do some more calculations to adjust the players golf handicaps based on these results too. basically, if there are 4 players, the winner has beaten 3 others, second has beaten 2 others, down to last place who has beaten no-one. the number of players you have beaten is multiplied by 10% of their handicap (not precisely this value, but something like it and makes easier to explain), then this adjustment is subtracted from the handicap to make a new handicap for the next comp. this works fine, so long as no-one is tied. but if 2nd and 3rd tie, then both players have effectively only beaten 1 other player (last placed). so i would want both to do "hcap - (1*(hcap*0.1))" for their handicap adjustment calculations. in my current code, even though they were tied, 2nd would have: "hcap - (2*(hcap*0.1))" 3rd would have: "hcap - (1*(hcap*0.1))" my current loop code is: $total_players = mysql_num_rows($r_lastcomp); $i = 1; while($row = mysql_fetch_array($r_lastcomp)){ echo "<br>"; $round_hcap = round($row[p_handicap]); SWITCH ($round_hcap){ CASE $round_hcap >= 0 AND $round_hcap <= 19: $multiplier = 0.1; break; CASE $round_hcap >= 20 AND $round_hcap <= 29: $multiplier = 0.2; break; CASE $round_hcap >= 30 AND $round_hcap <= 39: $multiplier = 0.3; break; CASE $round_hcap >= 40 AND $round_hcap <= 49: $multiplier = 0.4; break; } $hcap_reduce = ($total_players-$i)*$multiplier; $new_hcap = $row[p_handicap]-(($total_players-$i)*$multiplier); $sqlstr = "INSERT INTO dan_handicap VALUES (". $row[p_id]. ",". $row[r_id]. ",". $row[p_handicap]. ",". $i. ","; $sqlstr .= $total_players. ",". $hcap_reduce. ",". $new_hcap. ");"; $sqlstr2 = "UPDATE dan_player SET p_handicap = ". $new_hcap. " WHERE p_id = ". $row[p_id]. ";"; echo $sqlstr. "<br>"; echo $sqlstr2. "<br>"; $i++; } can anyone help with this please? my initial thoughts are i am going to need a drastic adjustment to the initial query add in position number in the comp, i.e. this would produce posn | name | score 1 | winner | 10 2 | tied 2nd | 8 2 | tied 2nd | 8 4 | last place | 5 the second section of code could then use this "position number" for the multiplier part of the calculations. apologies for the length of the post, but this covers the whole requirements. regards jingo_man Hello It's about exception handling... I have two if statements, one inside the other. And I want to throw an exception from each, if one of them is FALSE. What "technique" should I use? I think throwing same exception with the same message within two if's is a bit messy. like: if $x is true //go to 2nd if: if $y is true return value if $y is false: throw exception "Invalid number" if $x is false: throw exception "Invalid number" Thanks, Hi there. I am trying to display numbers if they have the numbers like: number_format($price,2) This gives us two decimal places i.e 7.23 Now thats fine, I would like to round the last two decimal places. I would like to make it 7.25, (rounding it from 7.23 to 7.25) Similarly making: 12.44 to 12.45 33.18 to 33.20 52.13 to 52.15 So actually rounding the last two places. Coz obviously customers won't be able to pay 52 dollars 13 cents. So therefore rounding the last cent's (decimal part) making it to 52.15 Thank you. All comments and feedback are welcomed. (d Hi there, I have a database with table column called EXPAMOUNT
if EXPAMOUNT value was £5.50 My code at moment echo “Total Expenses   £” . $row[‘SUM(EXPAMOUNT)’]. “ I'm making a connection to Active Directory using ADODB connection. I can read almost everything from this but some outputs are in an Octet format. For example objectSID is giving me only a ?. Is there somebody that knows how to read or convert this? I've found a converter function in ASP maybe someone can translate this to PHP? Code: [Select] TXT_ObjectGUID = HexStrToDecStr(OctetToHexStr(objRecordSet.fields("objectSID"))) Function OctetToHexStr(arrbytOctet) ' Function to convert OctetString (byte array) to Hex string. Dim k OctetToHexStr = "" For k = 1 To Lenb(arrbytOctet) OctetToHexStr = OctetToHexStr _ & Right("0" & Hex(Ascb(Midb(arrbytOctet, k, 1))), 2) Next End Function Function HexStrToDecStr(strSid) ' Function to convert hex Sid to decimal (SDDL) Sid. Dim arrbytSid, lngTemp, j ReDim arrbytSid(Len(strSid)/2 - 1) For j = 0 To UBound(arrbytSid) arrbytSid(j) = CInt("&H" & Mid(strSid, 2*j + 1, 2)) Next HexStrToDecStr = "S-" & arrbytSid(0) & "-" _ & arrbytSid(1) & "-" & arrbytSid(8) lngTemp = arrbytSid(15) lngTemp = lngTemp * 256 + arrbytSid(14) lngTemp = lngTemp * 256 + arrbytSid(13) lngTemp = lngTemp * 256 + arrbytSid(12) HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp) lngTemp = arrbytSid(19) lngTemp = lngTemp * 256 + arrbytSid(18) lngTemp = lngTemp * 256 + arrbytSid(17) lngTemp = lngTemp * 256 + arrbytSid(16) HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp) lngTemp = arrbytSid(23) lngTemp = lngTemp * 256 + arrbytSid(22) lngTemp = lngTemp * 256 + arrbytSid(21) lngTemp = lngTemp * 256 + arrbytSid(20) HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp) lngTemp = arrbytSid(25) lngTemp = lngTemp * 256 + arrbytSid(24) HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp) End Function Hi I need to convert hex or Decimal to Binary but can't find any function. Any one have one or ideas please. I need to round a number based on it's decimal. 3 or below should round down, 4 should round up to 5, 6 and 7 should round down to 5; 8 and 9 should round up to the next whole number. The below is returning 3 from 2.16. Code: [Select] <?php $a=2.16; $i=round($a, 1); $b=$i; $i=explode(".", $a); $decimal=$i[1]; if($decimal < 5){ $j=floor($b); $i= $decimal > 3 ? $j + .5 : $j; echo $i; } else{ $j=ceil($b); $i= $decimal < 8 ? $j - .5 : $j; echo $i; } ?> EDIT: The explode should have been on $i not $a. I'm hoping someone can show me how to get a random decimal number. I've googled and can't find anything that works. I need to find a random number between 1.0 and 10.0 I can get a random whole number no problem, but decimals aren't working. When I finally get that working, ideally I'd like to be able to find a random number between two decimals (like above) but also have a small chance of getting a decimal slightly higher than the two given. So, for example, maybe a random decimal between 3.5 and 6.0, but a slight chance of getting 6.2? Thank you very much for any help! I want to compute 150 + 20.95 * 1.01 + .5 so I get '171.65'. echo (150 + 20.95 * 1.01 + .5); gives me '171.6595'. I tried echo number_format(150 + 20.95 * 1.01 + .5, 2);, but I got '171.66'. How can I go about getting '171.65'? <?php $totalcreditstd = $row_rsCreditPurchaseMoney['SUM(quantity)']; $totalcreditsdollar = $totalcreditstd * $Mutliplier; echo $totalcreditsdollar; ?> I'm using the above calculation to display a total amount. Problem is that if the calculation total is 7.5 I want it to show up as 7.50 I want to force the second number. How can I do that? Thanks. I am comparing 2 decimal numbers I am pulling from a mysql file for ex $row[0]==$row1[0] every once in a while i get a bad positive when I do if($row[0]==$row1[0]) when they are exactly the same? One query is a SELECT amount FROM table the other is a select SUM(amount) FROM table2 any ideas why? ive tried making them both abs() when I print the out they are = Can someone five me the correct code or format to use that will allow my TINYINT columns to carry TWO decimal places when creating my table? I have a script for creating the table and columns, but only recently learned that I need to ADD the TWO decimal place FUNCTION in order to get whole dollar values to display WITH the trailing zeros (ie.:2.00). I don't expect to need any values greater than xxx.xx in my columns, I'm just not clear on how to get the desired script when running the initial CREAT script. Thanks |