Dennis98
Dennis98

Reputation: 139

PHP: Dividing/Multiplying/Rounding, not exact number

I made a survey page and there I'm reading the number of votes from a DB. Now I wanted to get the percentage of votes for displaying a "progress bar".

I wrote this funcion to get the percentage:

function progress($cur, $max, $round=1) {
    return ($max!=0) ? round(($cur/$max) *100, $round).'%' : '0%';
}

This seemed to be working fine, but for some numbers it adds many zeros and a 1 to the correct value. For example: 3/34 -> 8.800000000000001%. For other values (tested, 1,2,4,6) it's working correctly.

How can I correct this to display 8.8%?

Upvotes: 1

Views: 139

Answers (1)

WeSee
WeSee

Reputation: 3762

Use the sprintf function in PHP:

$formattedOutput = sprintf("%.1f",$floatValue);

gives you the the $floatValue with one decimal. see PHP manual for sprintf

Upvotes: 1

Related Questions