Erik
Erik

Reputation: 227

Rounding decimals in PHP

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?

Upvotes: 1

Views: 1101

Answers (7)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

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');}

Upvotes: 1

Cyclone
Cyclone

Reputation: 18305

You can use php's built in number_format

Upvotes: 0

NikiC
NikiC

Reputation: 101956

$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.

Upvotes: 2

KingCrunch
KingCrunch

Reputation: 132071

Have a look at sprintf()

$x = 0.4;
echo sprintf("%01.3f", $x);

Upvotes: 0

locrizak
locrizak

Reputation: 12279

You need

number_format($wpct, 3)

Upvotes: 1

oezi
oezi

Reputation: 51817

sounds like number_format is what you're looking for.

Upvotes: 0

konsolenfreddy
konsolenfreddy

Reputation: 9671

sprintf('%04d',$wpct1);

Will print leading zeros

Upvotes: 1

Related Questions