Jump to content

Problem echoing average


alexguz79

Recommended Posts

Hey everybody...

 

i am creating a website for the softball league i play in... and i have the batting average display with this code:

 

echo round(($totalhits."") / ($abs.""),3)

 

that takes the total hits and the total at bats and give me the average... the 3 is to limit the result to 3 figures insted of all the numbers in case of 0.333333333

 

the thing is i want to eliminate the 0 at the left of the dot... so it displays .333 insted of 0.333

 

the other thing is i want to display the complete number in case it's a round one... .400 insted of .4

 

thanks

Link to comment
Share on other sites

jesirose is right, number_format is your best bet, but that will only answer the second question. It will round and display X number of decimals. As for displaying the zero to the left of the decimal, that you'll have to get creative. This should do it:

$number = 0.3;
list($leftOfDecimal, $rightOfDecimal) = explode('.', round($number, 3));
if ($leftOfDecimal == 0){
  echo '.' . str_pad($rightOfDecimal, 3, STR_PAD_RIGHT);
} else{
  echo number_format($number, 3, '.', ',');
}

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.