0

I have an array of large integer values. When printed out with print_r(), the values are correct but when I assign the values inside of the array to variables and print with printf for precision, the values are different.

$this->v0 = $this->myArray[0];
$this->v1 = $this->myArray[1];
$this->v2 = $this->myArray[2];
$this->v3 = $this->myArray[3];

print_r($this->myArray);
printf("v0: %.0F | v1: %.0F | v2: %.0F | v3: %.0F\n", $this->v0, $this->v1, $this->v2, $this->v3);

this prints out

Array
(
    [0] => -8845908906223371573
    [1] => -7688304550669780974
    [2] => -7337754985657963041
    [3] => -8842903914599747060
)
v0: -8845908906223371264 | v1: -7688304550669780992 | v2: -7337754985657963520 | v3: -8842903914599746560

edit: I am on Mac OS X 10.11.3 and using PHP 7.0.4

Really not sure what is happening here but any help would be great. Thanks!

teknogeek
  • 103
  • 6
  • Your numbers are quite large, have you tried [BC Math](http://www.php.net/manual/en/book.bc.php) for floating point numbers or [GMP](http://www.php.net/manual/en/book.gmp.php) for integers? – Reece Kenney Mar 09 '16 at 13:21
  • The problem is definitely in your output style. In all the outputs just the 4 last digits are different so I'm suspicious to this: %.0F . This format is changing your numbers so try it with echo and see what happens. – DevMan Mar 09 '16 at 13:24
  • Yes I did try BC Math but again, It's hard to work with the values since they are changing as soon as I assign them to variables from the array. Are you suggesting that I instead store the numbers in GMP/BC Math class types inside the array from the start? – teknogeek Mar 09 '16 at 13:25
  • You are aware that floats notorious for bringing trouble? "So never trust floating number results to the last digit, " (See the big red warning: https://secure.php.net/manual/de/language.types.float.php). Though you are using integers with no digits after the decimal I highly suspect they will be rounded to their nearest float expression. See also this example: http://stackoverflow.com/a/18548882/1063730 – nuala Mar 09 '16 at 13:25

1 Answers1

3

Code

To fix your issue, you must use double %.0d instead of %.0f

$value = '-8845908906223371573';
print_r($value);
echo "\n";
printf("v0: %.0d",$value);
echo  "\n";

Output

-8845908906223371573
v0: -8845908906223371573
Kordi
  • 2,405
  • 1
  • 14
  • 13
  • thanks! that fixed the printing problem...so strange. now i'm having trouble with my addition of the numbers but that's for another question if I can't figure that out. i think i'll probably end up using GMP or BC Math for this. – teknogeek Mar 09 '16 at 13:28
  • 1
    @teknogeek yeah for addition I always use BC Math – Kordi Mar 09 '16 at 13:29