Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Php, how to get float value from a mixed string?

Tags:

string

php

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?

like image 579
Universal Grasp Avatar asked Jun 21 '14 13:06

Universal Grasp


People also ask

How can I get float in PHP?

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.

How can I convert string to float in PHP?

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 );

What is float val?

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)


2 Answers

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) 
like image 126
Danijel Avatar answered Sep 30 '22 06:09

Danijel


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.

like image 33
PeeHaa Avatar answered Sep 30 '22 07:09

PeeHaa