Flower
Flower

Reputation: 23

How can I return a percentage in PHP?

I'm having troubles how to properly return a percentage in PHP. I've tried using the sprintf function, although this only worked when I used decimals; how can I return a percentage in PHP using built in functions?

$percentage = sprintf('%3f', $completes / $incompletes);

Does not work. I've tried everything I could think of and all though this worked for decimals, it doesn't appear to work for integers...

Upvotes: 2

Views: 1213

Answers (5)

LF-DevJourney
LF-DevJourney

Reputation: 28559

Try this, live demo.

<?php
   echo sprintf('%.2f%%', 177.3333 / 100.0);

Upvotes: 0

Fran Cerezo
Fran Cerezo

Reputation: 948

$percentage = number_format($completes / $incompletes, 3) . '%';

Upvotes: 0

JYoThI
JYoThI

Reputation: 12085

%% - Returns a percent sign

$percentage = sprintf('%3f%%', $completes / $incompletes);

Upvotes: 1

phen0menon
phen0menon

Reputation: 2462

What about:

$percentage = ($completes / $incompletes) * 100;
echo $percentage . "%";

Upvotes: 2

Try this:

$percentage = sprintf("%01.3f", $completes / $incompletes);

Upvotes: 0

Related Questions