Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
更改php轮询结果的小数位数_Php_Decimal - Fatal编程技术网

更改php轮询结果的小数位数

更改php轮询结果的小数位数,php,decimal,Php,Decimal,下面是一段非常简单的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($

下面是一段非常简单的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.333%的结果。如何将其减少到小数点后一位


提前谢谢

PHP的数学库有一个round方法:

因此,在本例中,您将对结果进行四舍五入,并指定要将其保留到小数点后一位:

$rounded_value = round($result,1);
第一个参数是要舍入的值,第二个参数是小数位数-如果不需要小数位数,可以将其留空或使用0。

在乘以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>
你试过使用数字格式吗?比如$maybeepercentage=number_formatround$maybe/$votecount*100,1,1;例如:


结果将变成75.0

ps。我的php技能令人震惊,所以答案越简单越好!!:对不起,我不是很清楚,实际的代码是:%

你能把它编辑成小数点后一位吗?嗯,它似乎不起作用。我以为14是用来建立14个选项之间的平均值的?第二个参数是位数。你的括号也放错地方了。应该是%

$maybepercentage =  number_format(round(90 / 120* 100,1),1);
echo $maybepercentage;