drbae3964 2014-04-10 00:02
浏览 313
已采纳

PHP:将数字转换为百分比

I'm wanting to convert some numbers into a percentage of each other. The following code works some times but every so often it'll be off by a decimal place.

The problem is with the round(); function. From the example below you will see the percentage values add up to 100.01. This breaks my pie chart. :(

How may I fix this? So the corresponding percentage values will always hit 100 when added together.

$total['one']['value'] = '158';
$total['two']['value'] = '129';
$total['three']['value'] = '121';

$total['all'] = $total['one']['value'] + $total['two']['value'] + $total['three']['value'];

$total['one']['percent'] = round(($total['one']['value'] / $total['all']) * 100, 2);
$total['two']['percent'] = round(($total['two']['value'] / $total['all']) * 100, 2);
$total['three']['percent'] = round(($total['three']['value'] / $total['all']) * 100, 2);

Returns:

Array
(
    [one] => Array
        (
            [value] => 158
            [percent] => 38.73
        )

    [two] => Array
        (
            [value] => 129
            [percent] => 31.62
        )

    [three] => Array
        (
            [value] => 121
            [percent] => 29.66
        )

    [all] => 408
)
  • 写回答

1条回答 默认 最新

  • duangu9997 2014-04-10 00:22
    关注
    $total['three']['percent'] = 100-($total['one']['percent']+$total['two']['percent']);
    if($total['three']['percent'] < 0 && $total['two']['percent'] > 0-$total['three']['percent']){
        $total['two']['percent'] += $total['three']['percent'];
        $total['three']['percent'] = 0;
    }else if($total['three']['percent'] < 0){
        $total['one']['percent'] += $total['three']['percent'];
        $total['three']['percent'] = 0;
    }
    

    Demo with $total from OP: http://codepad.org/ydzpbHZr
    Additional demos with different values for precent: http://codepad.org/A9aUgniA and http://codepad.org/1bDaH4TX.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办