suttercain Posted March 1, 2007 Share Posted March 1, 2007 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 Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted March 1, 2007 Share Posted March 1, 2007 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 Quote Link to comment Share on other sites More sharing options...
Snooble Posted March 1, 2007 Share Posted March 1, 2007 make sure you fix the sp's in that. (spelling errors) Snooble Quote Link to comment Share on other sites More sharing options...
ToonMariner Posted March 1, 2007 Share Posted March 1, 2007 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... Quote Link to comment Share on other sites More sharing options...
suttercain Posted March 1, 2007 Author Share Posted March 1, 2007 Thanks guys. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.