Converting a large integer to a full string in PHP

I searched for a while, but what I can find is not what I am looking for. I need to convert an integer value, which can be very large, to a string. It sounds simple: "$var" ? No, because it can lead to the representation of an E+ number.

 <?php $var = 10000000000000000000000000; echo $var."\n"; echo "'$var'\n"; echo (string) $var."\n"; echo strval($var); ?> 

 1.0E+25 '1.0E+25' 1.0E+25 1.0E+25 

How can I conclude 10000000000000000000000000 instead?

+5
source share
4 answers

This is not saved as a PHP integer, but a float, so you get 1.0E + 25 instead of 10000000000000000000000000.

Unfortunately, it is not possible to use this as an integer value in PHP, since PHP cannot store an integer of this size. If it comes from a database, it will be a string, and you can do whatever you want with it. If you save it elsewhere, save it as a string.

Your alternative is to store it as a float and take this into account at all times, although this requires additional transformations and processing in places.

It has also been suggested to use GNU Multiple Accuracy , but this is not included by default in PHP.

 $int=gmp_init("10000000000000000000000000"); $string=gmp_strval($int); echo $string; 
+8
source

UPDATE: Found the following post:

 // strval() will lose digits around pow(2,45); echo pow(2,50); // 1.1258999068426E+015 echo (string)pow(2,50); // 1.1258999068426E+015 echo strval(pow(2,50)); // 1.1258999068426E+015 // full conversion printf('%0.0f',pow(2,50)); // 112589906846624 echo sprintf('%0.0f',pow(2,50)); // 112589906846624 

Use printf or sprintf .

+2
source

The integer you want to express:

 $var = 10000000000000000000000000; 

not available on your system. It is too large and therefore PHP will convert it to a float, which will change the number (an example of a 32-bit system):

  10000000000000000905969664 

General restrictions:

  yours : 10 000 000 000 000 000 000 000 000 32 bit: 2 147 483 648 64 bit: 9 223 372 036 854 775 808 

Changing the value is called floating point precision, the PHP manual on integers tells you about the integer limit and the floating point page on floating point precision (see big red warning). Depending on your system, you can compile PHP with the ranges required by your application, or you should use a different data type, for example, gmp library , which is able to select strings as integers and process them.

The following example shows only the output, but you can do multiplications, etc.:

 $r = gmp_init('10000000000000000000000000'); echo gmp_strval($r); 

Hope this will be helpful.

+2
source

I ran into this problem when getting facebook id and searching for it in MySQL. And after half an hour I found this job perfectly! Insert this line in your php script:

 ini_set('precision',30); 

From: https://forums.phpfreaks.com/topic/125907-solved-convert-big-number-to-string/#entry651084

+1
source

All Articles