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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.