Search code examples
phpmysqlaverage

SQL AVG() to 2 decimals


I'm trying to get this average to give me 2 decimals, so instead of 17.4534 I just get 17.45. I tried various combinations using CAST in each of the 2 places I use AVG in, but can't seem to get anything to work.

This is my code that currently works to give the average (just with too many decimals).

<?php
$sql3 = "SELECT AVG(app_tests.test_resultPercent) FROM app_tests"; 
$result3 = mysqli_query($conn,$sql3) or die(mysqli_error());
while($row3 = mysqli_fetch_array($result3))
    {
        echo "<h3>".$row3['AVG(app_tests.test_resultPercent)'];
    }
?>
</h3><p>Average % Lift</p>

Solution

  • Perhaps the ROUND() function would work?

    $sql3 = "SELECT ROUND(AVG(app_tests.test_resultPercent),2) FROM app_tests"; 
    

    EDIT

    Your PHP looks strange. You should either alias the average function as a column and access it by that name, or access it by index. Something like

    echo "<h3>".$row3[0];