views:

995

answers:

4

I'm trying to use a hardcoded 64bit integer in a string variable.

Simplfied I want to do something like this:

$i = 76561197961384956;
$s = "i = $i";

Which should result in s being:

i = 76561197961384956

This does obviously not work as PHP cast big integers to float, therefore s is:

i = 7.65611979614E+16

While several other methods like casting etc. fail, I found number_format() and use it like this:

$s = "i = " . number_format($i, 0, '.', '');

But this results in s being:

i = 76561197961384960

Looks like an approximation problem, but how to fix this?

+1  A: 

I think the only way is to use the bcmath functions.

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

It's your $i that's wrong, not the string conversion - PHP uses 32 bit ints internally.

Greg
A: 

Have you tried using the PHP's intval() function?

DV
+2  A: 

You're losing the precision on the assignment, not on the string conversion. If this variable's value is actually hardcoded, and you can't change that, there's nothing you can do.

A line like:

$i = 76561197961384956;

will always lose precision. If you need to keep the whole thing, store it into a string, you can't store it as an int like that and keep all the digits.

Chad Birch
+1  A: 

for now only way to do large integer math in php is to use bcmath or gmp extensions that handle large numbers as strings. 64bit integers are planed in php6.

so when using large integers cast them to string or you will lose precision on assigning ( automatic cast to float ) and then use on of the string math libraries to process your number further.

deresh