-2

That is my code below to get "100 power of 2 in PHP",

echo pow(2,100); 

I would get the result as 1.2676506002282E+30, However, I wish to get a whole integer of the result.

How should I do it with PHP?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Jim
  • 44
  • 1
  • 6
  • you want this `2^10 = 1024` ? – KUMAR Aug 04 '20 at 08:22
  • 2^100 , Kumar. but it will be converted to Scientific Expression due to its overflow, with PHP. pow() function. – Jim Aug 04 '20 at 08:32
  • I don't think so, CBroe. Appreciate your answer anyway. The solution is to use another function in PHP. (Ex: gmp_pow() or bcpow(). – Jim Aug 04 '20 at 08:34

2 Answers2

0

I guess by "accurate" you mean you want to get an exact integer. You will have to use additional library for working with big integers. GMP for example will work for what you need. It's is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating-point numbers.

Here is an example for the specific question:

<?php
    $pow = gmp_pow("2", 100);
    echo gmp_strval($pow);
?>

It will not work directly. You will have to first open php.ini and uncomment the "extension=gmp" line.

And that's not the only solution. There are more libraries available as variants for doing that.

Philip Petrov
  • 975
  • 4
  • 8
0

if by accurate, you want to have the exact value of 2 to the power of 100 that is equal to 1,267,650,600,228,229,401,496,703,205,376,

you can simply use

echo number_format(pow(2,100));

Update: like @Olivier said in comments, number_format does not return the exact results in some cases, so be careful in using that.

MaryNfs
  • 301
  • 3
  • 12
  • @Jim Be aware that `pow(2,100)` returns a float, not an integer. Which means you have no guarantee to get an exact result when you do that (although in this particular case, it does give the expected result). – Olivier Aug 04 '20 at 10:04
  • @Jim For example, `number_format(pow(3,40))` gives a wrong result. – Olivier Aug 04 '20 at 10:23