javascript 十进制数中只允许一个点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18149155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:53:13  来源:igfitidea点击:

Allow only a single point in decimal numbers

javascriptregex

提问by Abhishek Madhani

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)
  • 0
  • 0.13
  • 0.13.1(这应该是不允许的)

回答by Rohit Jain

Your regex doesn't matches what you say it matches. You have used negationin 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+)?$/

回答by Ry-

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.

但是你也可以只检查一个空字符串,无论如何它看起来更好。

回答by Leslie Jordaan

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

你可以试试下面的正则表达式 ^[-+]?\d*.?\d*$

回答by mehulcse

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

我想这应该做/^(\d*)\.{0,1}(\d){0,1}$//^(\d*)\.?(\d){0,1}$/

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

(\d*)表示小数点前的位数。

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

\.后跟{0,1}OR?将确保只有一个点。

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

(\d){0,1}小数点后只允许一位数。

回答by Derek

Try the following:

请尝试以下操作:

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

回答by Jatin patil

Try,

尝试,

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