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

javascript - Allow only a single point in decimal numbers - Stack Overflow

programmeradmin1浏览0评论

How can I modify this regular expression to allow numbers with just one point?

/[^0-9\.]/g

It currently allows:

  • 0
  • 0.13
  • 0.13.1 (this should not be allowable)

How can I modify this regular expression to allow numbers with just one point?

/[^0-9\.]/g

It currently allows:

  • 0
  • 0.13
  • 0.13.1 (this should not be allowable)
Share Improve this question edited Aug 9, 2013 at 14:34 Ry- 225k56 gold badges492 silver badges498 bronze badges asked Aug 9, 2013 at 14:31 Abhishek MadhaniAbhishek Madhani 1,1754 gold badges16 silver badges26 bronze badges 7
  • 1 There are so many similar questions linked on the right of this page. Didn't you see them when you were writing your question ? – Denys Séguret Commented Aug 9, 2013 at 14:35
  • 1 You don't need to escape a dot in a character class – HamZa Commented Aug 9, 2013 at 14:36
  • @dystroy, I did thorough search before posting, but none provided satisfiable answer. and none on the right point to what i am asking – Abhishek Madhani Commented Aug 9, 2013 at 14:38
  • stackoverflow./questions/10169147/… – Denys Séguret Commented Aug 9, 2013 at 14:44
  • Trying to find the duplicate, but this one is closed. Does it answer your question? Can you figure it out from the (pretty good) explanation there? – Ry- Commented Aug 9, 2013 at 14:46
 |  Show 2 more ments

6 Answers 6

Reset to default 12

Your regex doesn't matches what you say it matches. You have used negation in character class, and that too without any quantifier. Currently it would match any non-digit character other than ..

For your requirement, you can use this regex:

/^\d+(\.\d+)?$/

Make the match a positive one:

/^\d*(\.\d+)?$/

Any number of digits, optionally followed by a point and at least one digit. But it’s not worth it to keep a negative match.

If you want to disallow an empty string (which the original regular expression wouldn’t do), you could do this:

/^(?=.)\d*(\.\d+)?$/

But you could also just check for an empty string, which looks better anyways.

I guess this should do /^(\d*)\.{0,1}(\d){0,1}$/ OR /^(\d*)\.?(\d){0,1}$/

  • (\d*) Represents number of digits before decimal.

  • \. followed by {0,1} OR ? will make sure that there is only one dot.

  • (\d){0,1} Allows only one digit after decimal.

You can try the following regex ^[-+]?\d*.?\d*$

Try,

(value.match(/^\d+([.]\d{0,1})?$/))

Try the following:

/^(\d*)(\.\d*)?$/g
发布评论

评论列表(0)

  1. 暂无评论