Pass PHP variable to Python longer than 14 characters

Asked

Viewed 612 times

2

Problem passing Python variable to PHP over 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 contain up to 14 characters, e.g.: $p = 1234567891011, Python prints: 1234567891011

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

How will I recover the exact value of the variable when it exceeds 14 characters?

  • The strange thing is that the argument passed saw shell will be string, not an integer. I ran the code here and did not have the problem cited in the question. The code is only the same or hid parts of it?

  • @Anderson Carlos Woss, you tried to simulate with a number greater than or equal to 12345678910111213, because it may be a matter of Python version

  • @Bacco, I’m using PHP 7.0.4 x86

1 answer

6


You’re running into a numerical accuracy problem.

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

It turns out that even though 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, this is the directive:

php.ini file

precision 14

Link to the manual:

Directive precision


Using strings:

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

 $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 this, in the BCMATH and GMP library (see links below).


Relevant links:

How to get the highest numeric value supported by php?

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

Arbitrary accuracy in PHP with BCMATH

Arbitrary accuracy in PHP with GMP

  • 1

    Perfect, solved the problem, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.