PHP Convert String into Float/Double

前端 未结 4 1638
灰色年华
灰色年华 2020-12-30 01:00

I have list of string (size in bytes), I read those from file. Let say one of the string is 2968789218, but when I convert it to float it become 2.00.

This is my cod

相关标签:
4条回答
  • 2020-12-30 01:35

    $float = floatval($string);

    Ref : http://www.php.net/floatval

    0 讨论(0)
  • 2020-12-30 01:36

    Try using

    $string = "2968789218";
    $float = (double)$string;
    
    0 讨论(0)
  • 2020-12-30 01:41

    Surprisingly there is no accepted answer. The issue only exists in 32-bit PHP.

    From the documentation,

    If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

    In other words, the $string is first interpreted as INT, which cause overflow (The $string value 2968789218 exceeds the maximum value (PHP_INT_MAX) of 32-bit PHP, which is 2147483647.), then evaluated to float by (float) or floatval().

    Thus, the solution is:

    $string = "2968789218";
    echo 'Original: ' . floatval($string) . PHP_EOL;
    $string.= ".0";
    $float = floatval($string);
    echo 'Corrected: ' . $float . PHP_EOL;
    

    which outputs:

    Original: 2.00
    Corrected: 2968789218
    

    To check whether your PHP is 32-bit or 64-bit, you can:

    echo PHP_INT_MAX;
    

    If your PHP is 64-bit, it will print out 9223372036854775807, otherwise it will print out 2147483647.

    0 讨论(0)
  • 2020-12-30 01:55

    If the function floatval does not work you can try to make this :

        $string = "2968789218";
        $float = $string * 1.0;
        echo $float;
    

    But for me all the previous answer worked ( try it in http://writecodeonline.com/php/ ) Maybe the problem is on your server ?

    0 讨论(0)
提交回复
热议问题