Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Zero's and substr 1

Status
Not open for further replies.

maharamDan

IS-IT--Management
Mar 22, 2004
31
US
Hello. I am trying to figure out batting average. All works well for lets says 4/6. I get a .666 average.

But when is it something like 5/10 which is .5 That is when things go wrong.

How would I go about getting it displayed with zero's before the decimal? for example .500 batting average.
thanks in advance.
<code>
<?php
$hits = 5;
$at_bat = 10;
$div_value = $hits / $at_bat;

$average = substr("$div_value", 1, 4);
echo "$average";
?> </code>
 
Hi,

I don't understand the use of substr() here while or will solve the purpose.

Code:
<?php
$hits = 5;
$at_bat = 10;
$div_value = $hits / $at_bat;
printf("%.3f",$div_value) ;
?>


--------------------------------------------------------------------------
I never set a goal because u never know whats going to happen tommorow.
 
Spookie is right, using the substr() function seems kind of useless. If you're new to PHP, try going to the links that spookie gave you, at Their manual is really helpful for beginners (like me...).

Peace out,
Peace Co.
 
Hello and thank you for you help. I had that orginally but the result was still not what I wanted. I now get 0.500 or 0.234 I have to find out how to remove the leading zero. Thanks for the responses.
 
This is like way overkill bt works:

Code:
$hits = 1;
$at_bat = 2;
$div_value = $hits / $at_bat;

echo preg_replace('/^0/','',number_format($div_value,3));

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Thanks for the advice. I will try when I get home. Thanks again everyone.
 
spookie definitely has your answer... and if you're looking to store it in a variable for later printing rather than immediate output... then sprintf is the function you want.
 
But Spookies answer retains leading 0's ... /whistle

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
oh, and :
Display now:
Code:
echo preg_replace('/^0/','',number_format($div_value,3));

or
Code:
$data=preg_replace('/^0/','',number_format($div_value,3));
save it for later ...

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top