PHP: How to convert bigint from int to string?

天涯浪子 提交于 2019-11-27 15:31:22

You actually should ensure that you type what you mean:

$bigint = 9999999999999999999;

Is not a PHP integer but float:

float(1.0E+19)

If you would have done

$bigint = (int) 9999999999999999999;

You would have set an integer in fact, but it would not be the number you might have expected:

int(-8446744073709551616)

It's no problem at all to turn that into string as you might have guessed. So take care when you write numbers into code that you actually write what you mean.

See this line again:

$bigint = 9999999999999999999;

try to understand what you have actually written. It's not an integer at all because PHP will turn it into a float. See Example #4 Integer overflow on a 64-bit system in the integer manual page.

If you need higher precision, checkout GNU Multiple Precision, it might have what you're looking for. However, this won't change how to write numbers in PHP:

$bigint = gmp_init("9999999999999999999");
$bigint_string = gmp_strval($bigint);
var_dump($bigint, $bigint_string);

Output:

resource(4) of type (GMP integer)
string(19) "9999999999999999999"

Use strval().

echo strval($bigint); // Will output "99999999999999999"

EDIT: After a slightly better research (> 5000ms), I see that it is impossible to echo numbers to that precision, because PHP cannot save an integer of that size (depends on OS bit system, 32/64). Seems like it's not possible to do it without losing precision.

Use printf(), it's made for that:

echo printf("%d", $bigint);

Just store the value as string and display...!

   $bigint = '9999999999999999999';

    var_dump($bigint);

Output:

string(19) "9999999999999999999"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!