PHP:将 64 位整数转换为字符串

发布于 2024-07-20 16:11:31 字数 548 浏览 3 评论 0原文

我正在尝试在字符串变量中使用硬编码的 64 位整数。

简化我想做这样的事情:

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

这应该导致 s 为:

i = 76561197961384956

这显然不起作用,因为 PHP 将大整数转换为浮点数,因此 s 是:

i = 7.65611979614E+16

而其他几个像铸造等方法失败,我发现 number_format() 并像这样使用它:

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

但这会导致 s 是:

i = 76561197961384960

看起来像一个近似问题,但如何解决这个问题?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

长伴 2024-07-27 16:11:31

您会失去分配的精度,而不是字符串转换的精度。 如果这个变量的值实际上是硬编码的,并且您无法更改它,则您无能为力。

像这样的一行:

$i = 76561197961384956;

总是会失去精度。 如果您需要保留整个内容,请将其存储到字符串中,而不能将其存储为像这样的 int 并保留所有数字。

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.

旧伤还要旧人安 2024-07-27 16:11:31

我认为唯一的方法是使用 bcmath< /a> 函数。

对于任意精度的数学,PHP 提供了二进制计算器,它支持任何大小和精度的数字,以字符串表示。

这是你的 $i 错误,而不是字符串转换 - PHP 在内部使用 32 位整数。

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.

迷离° 2024-07-27 16:11:31

目前,在 php 中进行大整数数学运算的唯一方法是使用 bcmath 或 gmp 扩展来将大数字作为字符串处理。 64位整数在php6中被规划。

因此,当使用大整数时,请将它们转换为字符串,否则您将失去分配的精度(自动转换为浮点数),然后使用字符串数学库进一步处理您的数字。

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.

苍白女子 2024-07-27 16:11:31

您是否尝试过使用 PHP 的 intval() 函数?

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文