doushui3061 2011-08-22 17:35
浏览 685
已采纳

PHP:如何将bigint从int转换为string?

I want to be able to convert big ints into their full string derivatives.

For example.

$bigint = 9999999999999999999;
$bigint_string = (string) $bigint;
var_dump($bigint_string);

outputs

string(7) "1.0e+19"

but i need

string(19) "9999999999999999999"

Please don't tell me that I should just originally set the $bigint value as a string. That is not an option. I really am stuck and don't know if it is even possible?

  • 写回答

4条回答 默认 最新

  • douji9518 2011-08-22 17:48
    关注

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊