php precision with big numbers

Viewed 239

I have 2 big numbers 1133853003571025.63 and 1732254953579959.21 the sum of these numbers must be 2866107957150984.84
I'm working with php 5.6 and set the precision parameter to 16, but still php displays an incorrect output.

The output I'm getting is:
number 1: 1133853003571026
number 2: 1732254953579959
Sum : 2866107957150985
number 1 (format): 1133853003571025.75
number 2 (format): 1732254953579959.25
Sum (format): 2866107957150985.00
number length: 16

My code is

<?
$num01=1133853003571025.63;
$num02=1732254953579959.21;
$longitud= strlen($num01);
echo "number 1: ".$num01."<br>";
echo "number 2: ".$num02."<br>";
echo "Sum : ".($num01+$num02)."<br>";
echo "number 1 (format): ".number_format($num01, 2, '.', '')."<br>";
echo "number 2 (format): ".number_format($num02, 2, '.', '')."<br>";
echo "Sum (format): ".number_format(($num01+$num02), 2, '.', '')."<br>";
echo "<b>number length: </b>".$longitud."<br>";
?>

My question is what is wrong?, what is missing in my code?
1 Answers

PHP silently converts integer numbers that are too large for PHP to handle (> PHP_INT_MAX) to floats. This is by design.

Floating point values in PHP have limited precision. Take PHP_FLOAT_EPSILON into account when doing calculations with floats.

If all this does not suit your needs, take a look at the bcmath extention for arbitrairy precision. You could use it like this:

$a = '1133853003571025.63';
$b = '1732254953579959.21';
print bcadd($a, $b, 2);  // output: '2866107957150984.84'

An alternative to using bcmath is to let a database do the calculations, you could pass the calculation in an SQL SELECT statement and retrieve the results. Have a look at PDO.

MySQL / MariaDB example query:

SELECT CAST(1133853003571025.63 + 1732254953579959.21 AS CHAR) AS bignumber;
  -- result: '2866107957150984.84'

PostgreSQL example query:

SELECT (1133853003571025.63 + 1732254953579959.21)::text AS bignumber;
  -- result: '2866107957150984.84'
Related