Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  16] [ 6]  / answers: 1 / hits: 18011  / 13 Years ago, fri, october 7, 2011, 12:00:00

I'm trying to get a regex for an amount:



ANY DIGIT + PERIOD (at least zero, no more than one) + ANY DIGIT (at least zero no more than two [if possible, either zero OR two])



What I have is:



/^d+.{0,1}+d{0,2)+$/


...obviously not working. Examples of what I'm trying to do:



123 valid



123.00 valid



12.34.5 invalid



123.000 invalid



Trying to match an amount with or without the period. If the period is included, can only be once and no more than two digits after.


More From » regex

 Answers
23

Make the decimal point and 1 or 2 digits after the decimal point into its own optional group:



/^d+(.d{1,2})?$/





Tests:



> var re = /^d+(.d{1,2})?$/
undefined
> re.test('123')
true
> re.test('123.00')
true
> re.test('123.')
false
> re.test('12.34.5')
false
> re.test('123.000')
false

[#89737] Thursday, October 6, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;