Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a big integer to a full string in PHP

I've been searching for a while now, but what I can find is not what I search for. I need to convert an integer value, that may be very huge, to a string. Sounds easy: "$var"? No, because this can lead to the E+ representation of the 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 make the output be 10000000000000000000000000 instead?

like image 742
Niklas R Avatar asked Mar 08 '12 17:03

Niklas R


1 Answers

This is not stored as an integer by PHP, but a float, this is why you end up with 1.0E+25 instead of 10000000000000000000000000.

It's sadly not possible to use that as an integer value in PHP, as PHP cannot save an integer of that size. If this comes from database then it will be a string and you can do with it whatever you want. If you store it elsewhere then store it as a string.

Your alternative is to store it as a float and take that into account at all times, though that requires additional conversions and handling in places.

It's also been suggested to use GNU Multiple Precision, but that's not enabled in PHP by default.

$int=gmp_init("10000000000000000000000000");
$string=gmp_strval($int);
echo $string;
like image 146
kingmaple Avatar answered Oct 21 '22 14:10

kingmaple