Regular expression for numbers and one decimal
16,782
Solution 1
Updated answer:
RegExp -
^(?:0|[1-9]\d+|)?(?:.?\d{0,2})?$
Explanation at regex101:
Original answer:
RegExp -
^(\d+)?([.]?\d{0,2})?$
Explanation
Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference number 1 «(\d+)?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([.]?\d{0,2})?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the character “.” «[.]?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d{0,2}»
Between zero and 2 times, as many times as possible, giving back as needed (greedy) «{0,2}»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
Solution 2
Would this meet your needs:
var regex = /^\d+([.]?\d{0,2})?$/g;
Solution 3
Your regex:
var regex = /^\d+(\.\d{0,2})?$/g;
What you need:
var regex = /^\d*(\.\d{1,2})?$/;
You were requiring at least one digit before the decimal (\d+
). I have also changed it so if you include a decimal, there must be at least one digit after it.
Related videos on Youtube
Author by
Matthew Meppiel
Updated on September 16, 2022Comments
-
Matthew Meppiel over 1 year
I can't seem to get a simple regular expression to work. Here's what I have at the moment:
$(".Hours").on('input', function (e) { var regex = /^\d+(\.\d{0,2})?$/g; if (!regex.test(this.value)) { if (!regex.test(this.value[0])) this.value = this.value.substring(1, this.value.length); else this.value = this.value.substring(0, this.value.length - 1); } });
I need the user to be able to only enter numbers and one decimal (with only two numbers after the decimal). It's working properly now, with the exception that a user cannot start with a decimal.
Acceptable:
23.53 0.43 1111.43 54335.34 235.23 .53 <--- Not working
Unacceptable:
0234.32 <--- The user can currently do this 23.453 1.343 .234.23 1.453.23
Any help on this?
-
Blazemonger over 10 yearsWhy are you testing
this.value
andthis.value[0]
?
-
-
Dylan Vester almost 3 yearsThere is a minor bug in your regular expression. The decimal point wasn't escaped, so it was being processed as any single character. So it was allowing the number to start with basically anything (e.g. a24, b24, b50). Correct Regex
^(?:0|[1-9]\d+|)?(?:\.?\d{0,2})?$
-
Barry over 2 yearsThe regex doesn't work. 2.2, for example is not matched. Any single digit followed by '.' won't match. Your regex requires two digits before '.'.