最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript regex for amount - Stack Overflow

programmeradmin4浏览0评论

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
  • There are usually much better ways to detec a number. parseFloat for instance. – Madara's Ghost Commented Oct 7, 2011 at 16:01
  • @RikudoSennin parseFloat can be used as an attempt to convert a string to a number, possibly resulting in NaN, or an unwanted number. RegExps can be used to validate the string. – Rob W Commented Oct 7, 2011 at 16:03
  • Yes, though if parseFloat return a NaN that would probably mean that it's not a valid number. – Madara's Ghost Commented Oct 7, 2011 at 16:06
Add a comment  | 

3 Answers 3

Reset to default 19

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

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
}
发布评论

评论列表(0)

  1. 暂无评论