Jump to content

Regex: Is string a valid float


Stryks

Recommended Posts

I've come up with the following regex.  Just wondering if anyone can spot any problems or suggest any improvements.

 

preg_match('/\A(?:[\d]{0,3}(?:[,]{1}[\d]{3})*(?:[.]{1}[\d]*|[\d]+){1})\z/', $value)

 

It is intended to match numbers which are displayed with comma separators and an optional decimal point.

 

Cheers

Link to comment
https://forums.phpfreaks.com/topic/52284-regex-is-string-a-valid-float/
Share on other sites

Hehehe ... I know it's a bit ungainly, but it's still early days for me and regex (meaning I dont really how to comment it) so you'll have forgive the way it looks.  ;D

 

I had read through the isNumeric info and found that regex, however I dont actually want to mimic isNumeric because it doesn't do the job.

 

It allows hex values, and doesn't allow values like 1,234.56  In fact, it wont even validate 1.23.  The hex-free version ctype_digit is much the same, returning false for commas and decimal points.

 

It's going to be used for making sure form input is in a form that is expected, so I guess I just want to be sure that it isnt going to let through anything other than that expected value.

 

Cheers

It looks pretty good.. though it validates ",123".  I can't think of any nice way to fix that.  You could say

 

(1-3 digits OR (1-3 digits followed by 0-n sets of , and 3 digits)) followed by optional "." and so on

 

That way you ensure that commas always follow a digit group, while still making them optional.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.