How to add all values in this array?
If the value with the scientific notation 4.400...E+26
is commented out the result is 10171018899000
$list = [
700,
700,
200,
700,
2853300,
595300,
4736700,
1700,
4.4002258020009E+26,
200,
39800,
171002250300,
8410600,
100,
1000,
10000000000800,
100,
6000,
700,
100
];
print_r($list);
$sum = array_sum($list);
echo "sum: $sumn";
$sum = (int)$sum;
echo "sum: $sumn";
output
sum: 4.400225802001E+26
sum: -2402111299539435520
2
Answers
You could use utilize bcmath for large numbers and high preceision calculation. With the help of sprintf you can easily convert the notation to a string. Instead of array sum, we can use a reducer.
Demo: https://3v4l.org/ddJM9
The result you’re getting is not "completely wrong." It’s in scientific notation. The number 4.4002258020009E+26 is a very large number that is expressed in scientific notation (also known as exponential notation) for conciseness.
In scientific notation, 4.4002258020009E+26 is equivalent to 4.4002258020009 * 10^26, which is an incredibly large number.
When you’re printing the sum, PHP is using scientific notation for the output because it’s a convenient way to represent extremely large numbers.
If you want to see the result in standard decimal notation, you can use number_format() to format the output:
This will give you the sum in a more human-readable format. Also if the sum is still too large, you may encounter limitations in PHP’s floating-point precision.