Merlin
Merlin

Reputation: 199

How to round a number with 10 decimals to just 3 decimals after the comma

I extract an average from several table fields with the same characteristics, and I use the following code:

here is my code

 <? $query = 'SELECT AVG(points) FROM table1 WHERE id_user = '.$id_user.'';
    $avg = mysql_query($query, $conn) or die(mysql_error());
    $row = mysql_fetch_array($avg);?>

<b><?= $row['AVG(answer)']?></b> 

The thing is that sometimes this result is something like 8,1231452543635674563. My question is how can I make it to show only first 3 digits after the comma (ex: 8,123)? Thank you!

Upvotes: 0

Views: 104

Answers (2)

RolandoMySQLDBA
RolandoMySQLDBA

Reputation: 44363

Using just mysql, you could just use the FORMAT function:

<? $query = 'SELECT FORMAT(AVG(points),3) fmtavg FROM table1 WHERE id_user = '.$id_user.'';
   $avg = mysql_query($query, $conn) or die(mysql_error());
   $row = mysql_fetch_array($avg);?>

<b><?= $row['fmtavg']?></b> 

Upvotes: 1

jszobody
jszobody

Reputation: 28941

You just need number_format()

echo number_format($row['AVG(answer)'],3);

Also: you generally want to avoid short php tags like <?=. They make your code less portable, as many hosts don't have those enabled.

Upvotes: 2

Related Questions