Ste
Ste

Reputation: 1520

Find float number in string with php

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.

Upvotes: 0

Views: 1665

Answers (2)

Axel Isouard
Axel Isouard

Reputation: 1506

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

Upvotes: 1

hsz
hsz

Reputation: 152286

To match float value try following regexp:

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

Also you can just cast it to a float using:

$floatVal = (float) "8,742 MW";

Upvotes: 1

Related Questions