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.
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
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"
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)
You can use the following to check if a string is a float:
$a = "1.23";
$isFloat = ($a == (string)(float)$a);
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 stringFor 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!