Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Convert String into Float/Double

Tags:

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 code so far :

$string = "2968789218"; $float = (float)$string; //$float = floatval($string); //the result is same // result 2.00 

Anyone?

Solved

The problem was actually the encoding. It's fine now when I change the file encoding :D

like image 579
Bias Tegaralaga Avatar asked May 12 '13 18:05

Bias Tegaralaga


People also ask

How to convert string into float PHP?

Convert String to Float using floatval() To convert string to float using PHP built-in function, floatval(), provide the string as argument to the function. The function will return the float value corresponding to the string content. $float_value = floatval( $string );

How can I convert string to double in PHP?

You can use (int) or (integer) to cast a variable to integer, use (float) , (double) or (real) to cast a variable to float. Similarly, you can use the (string) to cast a variable to string, and so on. The PHP gettype() function returns "double" in case of a float for historical reasons.


1 Answers

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.

like image 178
Raptor Avatar answered Sep 24 '22 05:09

Raptor