drkbpwk609294 2014-03-20 03:40
浏览 217

在PHP中将字符串转换为float

I have a string value like this "0.00050722" and I want to convert its data type to double/float.

I've been trying floatval() and doubleval() but it always returns me a value of 0.

I need to get the exact of amount of 0.00050722 in a float datatype.

  • 写回答

2条回答 默认 最新

  • donglian1523 2014-03-20 04:32
    关注

    You just need to (typecast) to the desired type

        <?php
        $string = "0.00050722";
        $float = (float) $string;
        $float2 = $string + 0.0; //this works as well.
        $floatval = floatval($string);
        $double = (double) $string;
    
        // TEST
        printf("string:   %s - %d<br>", $string, is_float ($string));
        printf("float :   %g - %d<br>", $float, is_float ($float));
        printf("float2:   %g - %d<br>", $float2, is_float ($float2));
        printf("floatval: %g - %d<br>", $floatval, is_float($floatval));
        printf("double:   %g - %d<br>", $string, is_double ($double));
    
    ?>
    

    Should result in:

    string:   0.00050722 - 0
    float :   0.00050722 - 1
    float2:   0.00050722 - 1
    floatval: 0.00050722 - 1
    double:   0.00050722 - 1
    

    Notice that concatenation also works.

    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程