PHP:将数字转换为百分比

时间:2014-04-10 00:02:12

标签: php math rounding

我想将某些数字转换为彼此的百分比。以下代码有时可以工作,但每隔一段时间它就会被小数点所取代。

问题在于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
)

1 个答案:

答案 0 :(得分:1)

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

来自OP的$total演示:http://codepad.org/ydzpbHZr
具有precent {{1}} http://codepad.org/A9aUgniAhttp://codepad.org/1bDaH4TX的不同值的其他演示。