PHP:将 64 位整数转换为字符串 [英] PHP: Converting a 64bit integer to string
问题描述
我正在尝试在字符串变量中使用硬编码的 64 位整数.
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";
这应该导致 s
是:
i = 76561197961384956
这显然不起作用,因为 PHP 将大整数转换为浮点数,因此 s
是:
This does obviously not work as PHP cast big integers to float, therefore s
is:
i = 7.65611979614E+16
虽然其他几种方法(如强制转换等)都失败了,但我找到了 number_format()
并像这样使用它:
While several other methods like casting etc. fail, I found number_format()
and use it like this:
$s = "i = " . number_format($i, 0, '.', '');
但这导致 s
是:
i = 76561197961384960
看起来像是一个近似问题,但如何解决这个问题?
Looks like an approximation problem, but how to fix this?
推荐答案
您丢失了赋值的精度,而不是字符串转换的精度.如果该变量的值实际上是硬编码的,而您无法更改它,那么您将无能为力.
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.
像这样的一行:
$i = 76561197961384956;
总是会失去精度.如果你需要保留整个东西,把它存成一个字符串,你不能把它存成这样的 int 并保留所有的数字.
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.
这篇关于PHP:将 64 位整数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!