3

Is there any function that easily echos an integer that is 15+ digits long? The only way I've managed is like this:

$num = 123456789012345;
$num = number_format($num);
$num = str_replace(',', '', $num);
echo $num; 

But even this way it is only accurate up to 17 digits. After the 16th digit the number isn't printed accurately (because as a float it starts getting inaccurate - see here).

EDIT: From the answers below I wrote ini_set('precision',40); and then echoed $num straight. All this did was to, simply put, not show the decimal point in the float number. And again after the 16th digit it starts getting inaccurate. I also tried the other suggestion of changing it into an array and then iterating through it with str_split($num); and again the numbers were inaccurate from the 17th digit on!

The simplest solution would be to convert the integer into a string. I've tried:

$num = (string)$num; 
//and
$num = strval($num);

But neither change anything and they act as if as they remained as an int??

My question is specifically why are the conversions into strings not working. Is there a way to turn the number into a string? Thanks

Community
  • 1
  • 1
Ben
  • 515
  • 5
  • 18

2 Answers2

2

The only solution I can think of is changing the precision of floats in the php.ini

ini_set('precision', 25);

I don't know where you get those large numbers from, but I'd suggest a look into bc functions too!

The last thing I thought of is using the explode function to split the string into an array and interate through it.

EDIT: When all suggestions failed, your only choices are to check out the BC Math and/or GMP functions as well as MoneyMath. The BigInteger package should also do the trick, which uses GMP and BC.

manniL
  • 7,157
  • 7
  • 46
  • 72
0

Well, you see, it's not an "int" as you claimed :)

echo PHP_INT_MAX; // echoes 9223372036854775807
$n = 9223372036854775807;
echo $n; // echoes 9223372036854775807

$n = 9223372036854775808; 
echo $n; // echoes 9.2233720368548E+18

Setting precision to something greater, as manniL said, does the trick.

ini_set("precision", 50);
$n = 9223372036854775808; 
echo $n; // echoes 9223372036854775808
Community
  • 1
  • 1
Alexander Mikhalchenko
  • 4,525
  • 3
  • 32
  • 56