PHP - Using Ceiling Or Round Function For Decimals Places
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 Similar TutorialsHi.. 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 Code: [Select] $_POST['amount'] = intval($_POST['amount']); if ($_POST['amount'] < 0){ message($lang_common['Bad request']); } if (!is_numeric($_POST['amount'])){ message($lang_common['Bad request']); } echo $pun_user['gold']; echo '<br>'; echo $_POST['amount']; exit; if I enter 0.05 in my gold input textbox and submit it, it reads 0, it doesn't read the decimal values, i need it to read them, but I also need it to be secure and use intval.. help Hi, I have a page on which decimal values are entered. The problem is however that sql does not recognize the comma (the european decimal separator) as the decimal separator. How can I change the input to something that sql can accept? And what if someone enters a number in English format (a dot instead of a comma)? Or uses thousands-separators? Has anyone have experience with this? Greetz, Winelover Hello all it is my 1st post so welcome me i need to make php check if the number is 3 decimals and the last digit is 0. if it is 0 it will echo something if it is not 0 then it will echo something else i came up with this code but i dont know how to make it check if the decimal has a trail of 0 (zero) Code: [Select] <?php if(strpos($Price,".090") !== false){ echo "there is 0 at the end of the price"; //here code to remove the 0 if it is possible }else{ echo "there is no 0 at the end of the price"; // echo the normal price } ?> this will work correctly for the price $4.090 , 12.090 etc but how can i do it in php so it will check if there is 0 at the end of the decimal? Hi guys, I've got a line of code that asks for a column called "distance_completed" to be displayed as part of a string. This column tells users how far people have run in a running race. I set up this field in my database to 11,3 so all distances appear with a decimal at the end, and then 3 digits after the decimal place. How would I alter the code so that the numbers that don't have any information in the places section just appear as integers Eg: 42 instead of 42.000 (for someone who ran exaclty 42km) and those that do have information in the decimal places appear correctly (eg: if a person ran 42km and 195m, it would appear as 42.195). I think this is probably the only line of code that would need modification: Code: [Select] echo ($row['time'] != null)?$row["time"]:"dnf at ".$row["distance_completed"]."km."; Here is the number: $GrandTotal = "68.835"; $Deposit = round($GrandTotal , 2) * .5; echo $Deposit; I am looking for: 68.84 but the function doesn't seem to work right. Any help? Hi - To me, this doesn't make sense. My Order form uploads product weights in an array . If I echo out those weights they are fine ie 25.25 However, when I try to update the DB for some reason, the for loop strips out all but the first digit, so 25.25 becomes '2' or indeed if I had entered 9999999 it just '9' is entered in to the DB. I have tried using number_format to pre-process the decimals, - but I get an error saying you can not use it in a write format. Many Thanks to anyone who can help with this !! PS - I have abbreviated the below code for clarity: Code: [Select] $weight = $_POST['weight']; for ($i = 0; $i < $numloops ; $i++) { $sql =" UPDATE `confirmedorder` SET orderid = '$orderid[$i]', weight='$weight[$i]',status='finished', ordervalue='$ordervalue' WHERE customerid = $customerid "; $this->db->query($sql); } Just looking to know if this is the proper way to implement this: I need the below if to be true when any number between 100 and 1000 is the value of x, including say "105.55" if($x>= 100 && $x <= 1000){ } Basically I'm asking will a value of x with a decimal in it not cause the if statement to be true. I want to find the first sentence in a string without counting decimals. Here is the code I have, but I still want it to display the decimals, but I don't want it to count as the end of a sentence. $content = "This is my test string which is 3.5% of what I'm trying to do. This is only a test."; Code: [Select] function first_sentence($content) { if(preg_match('/[0-9]+\.[0-9]/', $content, $num)) { $number = "$num[0]"; $content = ereg_replace("$number","", $content); } preg_match('/^.*[^\s](\.|\?|\!)/U', $content, $match); $string = $match[0]; $title_count = strlen($match[0]); if($title_count > "6"){ return "$match[0]"; } else { $content2 = ereg_replace("$match[0]","", $content); preg_match('/^.*[^\s](\.|\?|\!)/U', $content2, $step); return "$match[0] $step[0]"; }} Currently this is what it displays: This is my test string which is % of what I'm trying to do. This is what I want it to display: This is my test string which is 3.5% of what I'm trying to do. Ok so say I have php do some calculations for me Code: [Select] $Value1 = 300; $Value2 = 100000; $FirstRatio = $Value1 / $Value2; $Value3 = 8000; $Value4 = 6000000; $SecondRatio = $Value3 / $Value4; $FirstRatio = 0.003 $SecondRatio = 0.0013 How would I go about doing these calculations and then sorting $FirstRatio and $SecondRatio and then it would take the highest ratio ($FirstRatio) and it would echo the value? 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? Hi, 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; } 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 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 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 know who to round a number to the nearest whole number, if i use echo round(9.5); it echo's 10 and if i use echo round(9.2); it echo's 9 i want it so it always rounds up? can anyone help? cheers matt hello guys, im creating a search result page that uses pagination, and im trying to figure out how many total pages their are going to be in my links with the page numbers. this is probably something really simple, ive been writing scripts for the last few hours and have a bit of a headache, any help would be appreciated here's the coding and the results i want: <?php $per_page = 10; $rows = mysql_query("SELECT COUNT(*) FROM articles WHERE text LIKE $string"); // this will return 31 $pages = $rows / $per_page; // returns 3.1 $total_pages = round($pages); // returns 3, want to round 3.1 up to 4 here ?> 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, |