ascripter
ascripter

Reputation: 6223

PHP: convert string to float (only if string represents a float)

I have an unknwon string that could resemble a float. In that case I want to convert it to float (for calculations), otherwise leave it as a string.

How do I detect if a string represents a float number?

$a = "1.23";        // convert $a to 1.23
$b = "1.2 to 1.3";  // leave $b as is

Automatic string conversion would convert the latter to 1.2, but that's not what I want.

Upvotes: 1

Views: 5699

Answers (5)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

Because it hasn't been mentioned

if(preg_match('/^\d+\.\d+$/', $string)){
   $float = (float)$string;
}

I think is_numeric is a better choice, but this works too.

What I have above only matches floats, so they have to have the decimal. To make that optional use /^\d+(\.\d+)?$/ instead.

  • ^ start of string
  • \d+ one or more digits
  • \. the dot, literally
  • \d+ one or more digits
  • $ end of string

For the second one /^\d+(\.\d+)?$/ it's the same as the above except with this addition:

  • (...)? optional capture group, match this pastern 0 or 1 times.

Which it should now be obvious is what makes the decimal optional.

Cheers!

Upvotes: 1

Wisang Jati Anggoro
Wisang Jati Anggoro

Reputation: 153

function StrToFloat($var){
    if(is_numeric($var)){
        return (float)$var;
    } else return $var;
} 

$a = "1.23";        // convert $a to 1.23
$b = "1.2 to 1.3";  // leave $b as is

$a = StrToFloat($a); // $a = 1.23
$b = StrToFloat($b); // $b = "1.2 to 1.3"

Upvotes: 2

Jamie Burton
Jamie Burton

Reputation: 515

You can use the following to check if a string is a float:

$a = "1.23";
$isFloat = ($a == (string)(float)$a);

Upvotes: 5

Pierrick Rambaud
Pierrick Rambaud

Reputation: 2394

maybe you would like to use the non-locale-aware floatval function:

float floatval ( mixed $var ) - Gets the float value of a string.

Example from the documentation:

$string = '122.34343The';
$float  = floatval($string);
echo $float; // 122.34343

Upvotes: 0

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

You can use is_numeric() function to check variable which might contain a number. For example:

$a = "1.23";
if (is_numeric($a)) {
    $a = (float)$a;
}

$b = "1.2 to 1.3";
if (is_numeric($b)) {
    $b = (float)$b;
}

var_dump([
    'a' => $a,
    'b' => $b
]);

Output

array (size=2) 'a' => float 1.23 'b' => string '1.2 to 1.3' (length=10)

Upvotes: 5

Related Questions