Jorge Zapata
Jorge Zapata

Reputation: 2336

Get float value without its unit of measure from a string

I've a list of strings of the following type:

27 km
56.1 km
45 KM
96.2km
87 k

And I want to get the numeric value for each one. As you can see some of them are float values, and the suffix "km" sometimes is mistyped. The output I'm looking for is the following:

27
56.1
45
96.2
87

I've found regular expressions on the web that convert a string to number but they don't consider that some values can be float, how can I write a function or find a expression that meets my requirements?

Upvotes: 1

Views: 4359

Answers (6)

Blake
Blake

Reputation: 2314

$var = floatval($float); is what you're looking for.

Upvotes: 3

eCoder
eCoder

Reputation: 1

try this. works for me

try {    
    Regex regexObj = new Regex(@"\b\d+(?:\.\d{0,}|)");    
    Match matchResults = regexObj.Match(subjectString);    
  while (matchResults.Success) {    
        // matched text: matchResults.Value    
        // match start: matchResults.Index    
        // match length: matchResults.Length    
        matchResults = matchResults.NextMatch();    
    }     
} catch (ArgumentException ex) {    
    // Syntax error in the regular expression    
}

php way

preg_match_all('/\b\d+(?:\.\d{0,}|)/', $subject, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
    # Matched text = $result[0][$i];
}

Upvotes: 0

jeroen
jeroen

Reputation: 91762

No need for a regex, just use floatval:

$float = floatval($string);

Upvotes: 4

Andrew Leach
Andrew Leach

Reputation: 12983

Just parseFloat() them. parseFloat() converts strings that start with a number to a number and stop with the first non-numeric character.

parseFloat('96.2 km') = 96.2

Upvotes: 2

Alexey
Alexey

Reputation: 683

Floating point regex: [-+]?[0-9]*\.?[0-9]+

Upvotes: 0

Aleks G
Aleks G

Reputation: 57336

For these strings, you can use /^\d+(\.\d+)?/

Upvotes: 0

Related Questions