Pass PHP variable to Python with more than 14 characters

2

Problem passing Python variable to PHP with more than 14 characters

PHP code

 $p = 123456789101112
 $pyscript = 'C:\Users\python\teste.py';
 $python = 'C:\Python34\python.exe';
 $run = shell_exec("$python $pyscript $p");

Python code

import sys
print(sys.argv[1])

If $p contains up to 14 characters, eg $p = 1234567891011 , Python prints: 1234567891011

But if there is more than 14, ex: $p = 12345678910111213 , Python prints: 1.2345678910111E+16

How can I retrieve the exact value of the variable when it exceeds 14 characters?

    
asked by anonymous 20.10.2017 / 00:42

1 answer

6

You're stumbling over a numerical precision problem.

PHP has a 32-bit integer value of 2147483647 , 64-bit value 9223372036854775807 and above it will have a float , with possible loss (see links at the end of the answer for more details).

It happens that even if the float can display a reasonable number of houses, there is a setting for displaying these, which by default is 14 . Once this length is exceeded, the display will be "abbreviated."

More specifically, the directive is this:

php.ini file

precision 14

Link to the manual:

  

Policy precision


Using strings :

One possible solution is to use a string instead of number. Passing the value as string output is textual, the numeric storage will be disregarded:

 $p = '123456789111315171921'; // note as aspas aqui
 $pyscript = 'C:\Users\python\teste.py';
 $python = 'C:\Python34\python.exe';
 $run = shell_exec("$python $pyscript $p");

If you really need to work with large numbers, PHP has specific functions for that, in the BCMATH and GMP libraries (see links below).


Relevant links:

  

How to get the highest numeric value supported by php?

  

What is the maximum number of decimal places allowed in the float in PHP?

  

Arbitrary Accuracy in PHP with BCMATH

  

Arbitrary Precision in PHP with GMP

    
20.10.2017 / 02:38