我做了一个调查页面,我在那里读取数据库中的投票数。 现在我想获得显示"进度条的投票百分比"。
我写了这个函数以获得百分比:
function progress($cur, $max, $round=1) {
return ($max!=0) ? round(($cur/$max) *100, $round).'%' : '0%';
}
这似乎工作正常,但对于某些数字,它会添加许多零和1到正确的值。 例如:3/34 - > 8.800000000000001%。对于其他值(测试,1,2,4,6),它正常工作。
如何更正此显示8.8%?
答案 0 :(得分:1)
在PHP中使用sprintf函数:
$formattedOutput = sprintf("%.1f",$floatValue);
为您提供带有一位小数的$ floatValue。 见PHP manual for sprintf