Jump to content

[SOLVED] Average of three numbers with precision of two decimal places


suttercain

Recommended Posts

Good morning,

 

I figured out how to average three (or more) numbers:

<?php
//The Three Numbers to Be Averaged
$num1 = 25;
$num2 = 50;
$num3 = 100;

//Average Output
$total = (($num1 + $num2 +$num3) / 3);

echo "$total";
?>

 

The above code outputs: 58.3333333333

 

How can I get it to the precision of two decimal places? EXP. 58.33 instead of 58.3333333333

 

Do I use the (float) operator?

 

Thanks in advance.

 

Shannon

Link to comment
Share on other sites

If you are a little cleaver you can allow this to do more...

 

Say you use input boxes to enter your numbers...

 

<input type="text" name="number[]" />

 

Now if the form posts to your script you can do this...

 


$ave = (array_sum($_POST['number']) / count($_POST['number']));

echo number_fomat($ave,2).'<br>';
print_f("%01.2f",$ave);

 

Just lets you add as many numbers as you like...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.