0

I have these strings:

$txt1 = "8,742 MW";
$txt2 = "7,750 KW";
$txt2 = "2,350 GW";

I need a regex to find the valid float number into these strings... How can I do it ? Thanks.

1

2 Answers 2

1

To match float value try following regexp:

(\d+(?:,\d+)?)

Also you can just cast it to a float using:

$floatVal = (float) "8,742 MW";
Sign up to request clarification or add additional context in comments.

2 Comments

if (preg_match("(\d+(?:,\d+)?)", $txt1, $matches)) { $value = $matches[0]; print "value=$value\n"; }
$floatVal = (float) "8,742 MW"; // It will work if you replace the ',' by '.'
1

This one should do it :

[-+]?([0-9]*\,)?[0-9]+

Or if you'd like to convert directly to a float by taking the comma "," as a dot ".", then I think you should set your locale to a french one as stated here :

setLocale(LC_ALL, 'fr_BE.UTF-8');

Comments

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.