1

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.

1

5 Answers 5

5

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)

Sign up to request clarification or add additional context in comments.

Comments

5

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

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

Comments

2
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"

1 Comment

Actually the same like @Maxim's answer, only nicely wrapped inside a function.
1

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!

Comments

0

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

2 Comments

I don't see how this works. floatval($string) == $string seems to be always true.
normally it only return a float (0 if its not numeric and the value of the float) but by rereading your post I realize that the $b = "1.2 to 1.3" will also return 1.2sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.