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

Use either number_format() or [http://www.php.net/printf]printf()[/url] functions:

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

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

echo number_fomat($total,2).'<br>';
printf("%01.2f",$total);
?>

 

Ken

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...

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.