php : result of sum array values is wrong -
i have array:
$test =array('49'=> '-0','51'=> '-0','50'=> '0','53'=> '-1.69','55'=> '0','57'=> '-2','59'=> '-6','60'=> '-12','65'=> '0','66'=> '0','67'=> '21.69','69'=> '0','70'=> '0','71'=> '0',); echo "\n".'===== first method ========'; echo "\n\n".print_r($test); echo "\n array_sum: ".array_sum($test); echo "\n\n".'===== second method ========'; $total = 0;foreach($test $value) $total += $value; echo "\n foreach:".$total."\n";
the result
gd@gd:~/desktop$ php test.php ===== first method ========array ( [49] => -0 [51] => -0 [50] => 0 [53] => -1.69 [55] => 0 [57] => -2 [59] => -6 [60] => -12 [65] => 0 [66] => 0 [67] => 21.69 [69] => 0 [70] => 0 [71] => 0 ) 1 array_sum: 3.5527136788005e-15 ===== second method ======== foreach:3.5527136788005e-15
it wrong, result should 0, not 3.5527136788e-15, how fix ?
this standard floating point arithmetic precision error.
php -r "echo -1.69 + -2 + -6 + -12 +21.69;" 3.5527136788005e-15%
you can fix using ints rather floats. example, if expect 2 digits of precision, multiply numbers 100, round them off ints, sum them, , divide 100.
php -r "echo (-169 + -200 -1200 +2169 + -600) / 100;" 0%
Comments
Post a Comment