PHP:将数字转换为百分比

同上

我想将一些数字相互转换成一个百分比。以下代码有时会起作用,但每隔一段时间就会用小数点后一位。

问题出在round();功能上。在下面的示例中,您将看到百分比值总计为100.01。这打破了我的饼图。:(

我该如何解决?因此,相加后,相应的百分比值将始终达到100。

$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);

返回值:

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

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

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

    [all] => 408
)
穆斯曼
$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;
}

演示与$total来自OP:http://codepad.org/ydzpbHZr
具有不同值的附加的演示供precenthttp://codepad.org/A9aUgniAhttp://codepad.org/1bDaH4TX

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章