I got a string like:
$str = "CASH55.35inMyPocket";
I want to get 55.35 only.
I tried:
$str = floatval("CASH55.35inMyPocket");
if ($str > 0) {
echo "Greater_Zero";
} else {
echo "LessZERO!!";
}
// echo "LessZERO!!";
I also tried:
$str = (float)"CASH55.35inMyPocket";
if ($str > 0) {
echo "Greater_Zero";
} else {
echo "LessZERO!!";
}
// echo "LessZERO!!";
According to the Documentation:
Strings will most likely return
0
although this depends on the leftmost characters of the string.
So, flotval
and (float)
apparently only work if the string is something like:
55.35aAbBcCdDeEfF
... but will NOT work if it is like: aAbBcC55.35dDeEfF
is there a way to get the float no matter the position of text?
Method 1: Using floatval() function. Note: The floatval() function can be used to convert the string into float values . Return Value: This function returns a float. This float is generated by typecasting the value of the variable passed to it as a parameter.
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 );
A floating point value is represented either as whole plus fractional digits (like decimal values) or as a mantissa plus an exponent. The following is an example of the mantissa and exponent parts of floating point values: There are two floating point data types: • float4 (4-byte) • float (8-byte)
If you dont want to use regular expressions use filter_var:
$str = "CASH55.35inMyPocket";
var_dump( (float) filter_var( $str, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) ); // float(55.35)
What you have cannot be casted to a float, because it doesn't look like a float from PHP's perspective. It is possible to grab the value using regex though.
If you are not sure whether there will always be a decimal. And you are trying to get the number regardless of position in the text (as per your question). You could use:
^.*?([\d]+(?:\.[\d]+)?).*?$
Which gets the numeric values from the following strings:
CASH55.35inMyPocket
CASH55inMyPocket
55.35inMyPocket
55inMyPocket
inMyPocket55.35
inMyPocket55
Explanation: http://regex101.com/r/tM8eM0
Demo: http://rubular.com/r/Gw5HTzsejj
PHP demo: https://eval.in/165521
Basically it looks for numbers in the string. And optionally it also check for decimals after that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With