2

I have seen many links for floating point number validation but none of them for precision.

only floating point number validation

I want the field to display error if the input is 1234.31 or . but not for 123.5555555 or .3433 or.9022. I need the rules to be specified to get 0 to 3 digit before decimal. I tried

/^[^+-][0-9]{0,3}[.]?[0-9]{0,2}/

But it didn't work.

Community
  • 1
  • 1
Abel
  • 2,371
  • 3
  • 15
  • 29

2 Answers2

2

Use this regex:

/^\d{0,3}\.\d+/

But if you want to use your regex, modify it like this:

/^[^+-][0-9]{0,3}[.]?[0-9]+/

Your original regex didn't work because you were making it to match only up to 2 decimal places. + in regex means 1 or many.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

You pretty much had it

/^([0-9]{0,3})?\.[0-9]+|[0-9]+$/

and use something like

if(!preg_match("^([0-9]{0,3})?\.[0-9]+|[0-9]+$/", $float)){}
Class
  • 3,149
  • 3
  • 22
  • 31
  • Thanks, my concern is not much about the digits after decimal. Is that possible to make it accept digits without decimals as well, but not accepting a plain "." – Abel Apr 03 '14 at 06:35
  • @Abel Try my regex out and see for yourself but use a `!` 'not'. Or use this [test](https://www.debuggex.com/r/8dERfrSGUczd1ZBW) here by changing the `result` item. – Class Apr 03 '14 at 06:38