2014-04-10 202 views
0

我想将一些数字转换为彼此的百分比。下面的代码工作了一段时间,但每隔一段时间它就会被小数点后的位置关闭。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 
) 
+0

总是有三个值吗? – Mooseman

+0

是的,但我认为它应该能够处理任何金额。 – ditto

+0

可能重复[浮点数学是否被破坏?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) –

回答

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

演示与$total从OP: http://codepad.org/ydzpbHZr
具有不同值的其他演示precenthttp://codepad.org/A9aUgniAhttp://codepad.org/1bDaH4TX