0

average rating

Here is my code! How do I get the average that has only 2 decimal places?
public function getAveRating($restoid) { $where = array( "restoid" => $restoid ); $this->db->where($where); $this->db->select_avg('rate'); $query = $this->db->get('ratings')->first_row('array'); return $query['rate']; } 

How do I limit the average into 2 decimal places in getting the rating?

0

3 Answers 3

0

http://php.net/round

 public function getAveRating($restoid){ $where=array( "restoid"=>$restoid ); $this->db->where($where); $this->db->select_avg('rate'); $query = $this->db->get('ratings')->first_row('array'); return round($query['rate'], 2); } 
Sign up to request clarification or add additional context in comments.

Comments

0

Change return $query['rate']; to return round($query['rate'],2);

Comments

0

You can call number_format() on the lone returned value from your query if you want a formatted string with thousands placeholders otherwise use round() to return a float value.

public function getAveRating(int $restoid): float { return round( $this->db ->select_avg('rate') ->get_where('ratings', ['restoid' => $restoid]) ->row('rate'), 2 ); } 

Or you could round in the query itself.

public function getAveRating(int $restoid): float { return (float)$this->db ->select('ROUND(AVG(rate), 2) rate') ->get_where('ratings', ['restoid' => $restoid]) ->row('rate'); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.