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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?