I want to display a number as a winning percentage, similar to what you would see on ESPN baseball standings. If the user has no losses, I would like the percentage to read 1.000. If the user has no wins, I would like it to read .000. If the user has a mix of wins and losses, I would like to display .xyz, even if y or y and z are 0's.
This code gets me no trailing 0's, and also a 0 before the decimal (0.4 instead of .400, 0.56 instead of .560):
$wpct1 = $wins / ($wins + $losses);
if($wpct1 == 1){$wpct = '1.000';}else{$wpct = round($wpct, 3);}
This code gets the initial 0 befoer the decimal out of there, but still no trailing zeroes (.4 instead of .400):
$wpct1 = $wins / ($wins + $losses);
if($wpct1 == 1){$wpct = '1.000';}else{$wpct = substr(round($wpct, 3), 1, 4);}
This second solution is getting me closer to where I want to be, how would I go about adding the trailing 0's with an additional piece of code (one or two trailers, depending on the decimal), or is there another way to use round/substr that will do it automatically?
$wpct = ltrim(number_format($wins / ($wins + $losses), 3), '0');
This formats the number the three digit after the decimal point and removes any leading zeroes.
See number_format
and ltrim
for further reference.
sprintf('%04d',$wpct1);
Will print leading zeros
sounds like number_format is what you're looking for.
You need
number_format($wpct, 3)
Have a look at sprintf()
$x = 0.4;
echo sprintf("%01.3f", $x);
You can use php's built in number_format
You could use str_pad() to add trailing zeros like this:
if($wpct1 == 1){$wpct = '1.000';}else{$wpct = str_pad(substr(round($wpct, 3), 1, 4), 3, '0');}