我有一段非常简单的PHP轮询脚本的代码
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td><img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes+$maybe),3)); ?>'
height='20'> <?php echo(100*round($yes/($no+$yes+$maybe),3)); ?>% </td>
</tr>
<tr>
<td>No:</td>
<td><img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes+$maybe),3)); ?>'
height='20'> <?php echo(100*round($no/($no+$yes+$maybe),3)); ?>% </td>
</tr>
<tr>
<td>Maybe:</td>
<td><img src="poll.gif"
width='<?php echo(100*round($maybe/($no+$yes+$maybe),3)); ?>'
height='20'> <?php echo(100*round($maybe/($no+$yes+$maybe),3)); ?>% </td>
</tr>
<tr>
</table>
然而,如果他们都有相同数量的选票,我得到的结果如33.333333333%。如何将其减少到只有一位小数?
提前致谢!
答案 0 :(得分:0)
PHP的Math库有一个圆形方法:
http://www.php.net/manual/en/function.round.php
所以在这种情况下,你会在结果上调用round并指定你想要它到一个小数位:
$rounded_value = round($result,1);
第一个参数是要舍入的值,第二个是小数位数 - 如果不需要小数位,可以将其留空或使用0。
答案 1 :(得分:0)
使用round后乘以100,而不是之前。
<?php echo round(($no/($no+$yes+$maybe) * 100 ),1) ; ?>
你的代码也可以简化一点,就像这样
<?php
$votecount = $no+$yes+$maybe;
$yespercentage = round($yes / $votecount * 100,1);
$nopercentage = round($no / $votecount * 100,1);
$maybepercentage = round($maybe / $votecount * 100,1);
?>
<table>
<tr>
<td>Yes:</td>
<td><img src="poll.gif"
width='<?php echo $yespercentage; ?>'
height='20'> <?php echo $yespercentage; ?>% </td>
</tr>
<tr>
<td>No:</td>
<td><img src="poll.gif"
width='<?php echo $nopercentage; ?>'
height='20'> <?php echo $nopercentage; ?>% </td>
</tr>
<tr>
<td>Maybe:</td>
<td><img src="poll.gif"
width='<?php echo $maybepercentage; ?>'
height='20'> <?php echo $maybepercentage; ?>% </td>
</tr>
<tr>
</table>
答案 2 :(得分:0)
您尝试使用number_format()
吗?像$maybepercentage = number_format(round($maybe / $votecount * 100,1),1);
例如:
$maybepercentage = number_format(round(90 / 120* 100,1),1);
echo $maybepercentage;
结果将变为75.0