Berit Larsen
Berit Larsen

Reputation: 752

Unable to convert string to float in php

I'm trying to convert a String with a number into a float. I tried the following:

write_file($log . "temp=" . $temp . ".<br/>" , "public/files/log.txt" );
write_file($log . "temp type=" . gettype($temp) . "<br/>" , "public/files/log.txt" );
$flyt  = floatval("2.19");
write_file($log . "2.19 float =" . $flyt . ".<br/>" , "public/files/log.txt" );
$flyt  = floatval($temp);
write_file($log . "temp float =" . $flyt . ".<br/>" , "public/files/log.txt" );

Which gives me the following results:

temp float =0.
2.19 float =2.19.
temp type=string
temp=2.19.

When $temp is "2.19", why can't I get it to float? I've tried several methods, none work. What am I doing wrong?

Upvotes: 0

Views: 2446

Answers (2)

aMighty
aMighty

Reputation: 283

You can use typecasting.

$StringVal = "10.12";   // $StringVal is String
$FloatVal = (float) $StringVal;   // $FloatVal is Float

You can use this function to convert string variable to float.

This function takes the last comma or dot (if any) to make a clean float, ignoring a thousand separators, currency or any other letter:

function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos : 
        ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);

    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    } 

    return floatval(
        preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
        preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
    );
}

Reference : http://php.net/manual/en/function.floatval.php

PTR when using floatval():

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.

Upvotes: 0

Ranadip Dutta
Ranadip Dutta

Reputation: 9351

Go through this Documentation: String Convertions

This Should do that:

$flyt = (float) "2.19";

For floatval :

$string = '2.19';
$flyt  = floatval($string);
echo $flyt;

Have a look at FloatVal Examples too.

Upvotes: 2

Related Questions