Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum array values more than 15 digits using array_sum in php

Tags:

php

I have to sum values of an array. I have an array

$arr = array('0' => 87.85749999999999823, '1'=>1); print_r(array_sum($arr));

And I am getting output as 88.8575, but I am expecting as 88.85749999999999823

Thanks for any help.

like image 249
Tushar Avatar asked Oct 20 '22 03:10

Tushar


1 Answers

the float is limited at 14 digit. if you need more accuracy, try the BC Math library

<?php
echo "<br/>float<br/>";
$arr = array('0' => 87.85749999999999823, '1'=>1);
print_r(($arr));
print_r(bcadd($arr[0], $arr[1], 20));

echo "<br/>BCMath<br/>";
$arr = array('0' => "87.85749999999999823", '1'=>"1");
print_r(($arr));
print_r(bcadd($arr[0], $arr[1], 20));
like image 52
mmm Avatar answered Nov 01 '22 15:11

mmm