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.
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.
Share Improve this question asked Oct 7, 2011 at 15:57 OseerOseer 7407 gold badges19 silver badges28 bronze badges 3 |3 Answers
Reset to default 19Make 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
Have you tried:
/^\d+(\.\d{1,2})?$/
The ?
makes the group (\.\d{1, 2})
optional (i.e., matches 0 or 1 times).
Would something like this work?
// Check if string is currency
var isCurrency_re = /^\s*(\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/;
function isCurrency (s) {
return String(s).search (isCurrency_re) != -1
}
parseFloat
for instance. – Madara's Ghost Commented Oct 7, 2011 at 16:01parseFloat
can be used as an attempt to convert a string to a number, possibly resulting inNaN
, or an unwanted number. RegExps can be used to validate the string. – Rob W Commented Oct 7, 2011 at 16:03NaN
that would probably mean that it's not a valid number. – Madara's Ghost Commented Oct 7, 2011 at 16:06