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
https://forums.phpfreaks.com/topic/208222-problem-echoing-average/
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, '.', ',');
}

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.