2

Trying to convert 9769712680 Bytes to Gigabytes. I have the following code:

$value = 9769712680 / (1024 * 1024 * 1024);

This should give a value of 9 Gb but instead it gives 2047 Mb (or 2 Gb).

Also tried: 9769712680 / 1024 / 1024 / 1024 but this also does the same thing.

Any ideas?

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • 3
    Are you on a 64-bit or 32-bit system? The max integer size on a 32-bit system is 2147483647, or about 2G. – Connor McArthur Mar 19 '13 at 22:18
  • duplicate of http://stackoverflow.com/questions/211345/working-with-large-numbers-in-php ? – MatRt Mar 19 '13 at 22:20
  • 2
    This should still work though, PHP represents numbers outside the bounds of a signed int with a float. I've just tried `echo 9769712680 / (1024 * 1024 * 1024);` on a Windows system using a 32-bit build, and it results in the expected `9.0987...`. Can you show where you obtained the data from? Avoid casting anything to an integer, as this will trim the value back into bounds. – DaveRandom Mar 19 '13 at 22:27

4 Answers4

5

9769712680 - you have integer overflow here, so it becomes 2^31, the max int value.

Andrey
  • 59,039
  • 12
  • 119
  • 163
  • im on a 64bit system , data is from a XML file using foreach to load the value and then $value = 9769712680 / (1024 * 1024 * 1024); – user2080473 Mar 19 '13 at 22:43
  • @user2080473 What is exact type of number? It is very clear that you get somehow max int32 instead of your number. – Andrey Mar 19 '13 at 22:46
  • 9769712680 is axact number If i do $value=$test; echo "$test" I get the number 9769712680 – user2080473 Mar 19 '13 at 22:57
  • @user2080473 your code returns 9.something: http://phpfiddle.org/main/code/eqs-nnx so you are missing something here. – Andrey Mar 19 '13 at 22:59
  • what can i miss if its pretty straight forward... value = 9769712680 / (1024 * 1024 * 1024) – user2080473 Mar 19 '13 at 23:07
  • @user2080473 open my link and see what you miss. Your code produces correct output, not the one you mention in your question. – Andrey Mar 19 '13 at 23:08
0

Looks like the initial number is represented as a int32. Doing some math (using Matlab):

9769712680/(1024*1024*1024) = 9.09875396639109

double(int32(9769712680))/(1024*1024*1024) = 2
Pursuit
  • 12,285
  • 1
  • 25
  • 41
0

I don't know why this is not represented right (it does work for me).
Anyway you can use the BC Math library, which is commonly compiled with PHP, to solve equations with numbers of any length.

In your case it would look like this:

$value = bcdiv('9769712680', '1073741824', 4); /// 1024^3=1073741824
dan-lee
  • 14,365
  • 5
  • 52
  • 77
0

You may use the BCMath library:

$bytes = '976971268097697126809769712680976971268097697126809769712680';
$Gb = bcdiv($bytes, bcpow(1024, 3), 2);
echo $Gb; // 909875396730096197509923682250992368225099236822509.92
HamZa
  • 14,671
  • 11
  • 54
  • 75