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!

4
  • Your numbers are quite large, have you tried BC Math for floating point numbers or GMP for integers? Commented Mar 9, 2016 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. Commented Mar 9, 2016 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? Commented Mar 9, 2016 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: 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: stackoverflow.com/a/18548882/1063730 Commented Mar 9, 2016 at 13:25

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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 yeah for addition I always use BC Math

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.