javascript 小数的Javascript正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15134795/
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
Javascript Regex for decimals
提问by ChrisCa
In Javascript, I am trying to validate a user input to be only valid decimals
在 Javascript 中,我试图验证用户输入是否仅是有效的小数
I have the following JSFiddle that shows the regex I currently have
我有以下 JSFiddle 显示了我目前拥有的正则表达式
var regex = /^[0-9]+$/i;
var key = '500.00';
if (key.match(regex) != null) {
alert('legal');
}
else {
alert('illegal');
}
This works fine for integers. I need to also allow decimal numbers (i.e. up to 2 decimal places)
这适用于整数。我还需要允许十进制数(即最多 2 个小数位)
I have tried many of the regex's that can be found on stackoverflow e.g. Simple regular expression for a decimal with a precision of 2
我已经尝试了许多可以在 stackoverflow 上找到的正则表达式,例如 精度为 2 的小数的简单正则表达式
but none of them work for this use case
但它们都不适用于这个用例
What am I doing wrong?
我究竟做错了什么?
回答by Prashant16
This should be work
这应该是工作
var regex = /^\d+(\.\d{1,2})?$/i;
回答by orique
Have you tried this?
你试过这个吗?
var regex = /^[0-9]+\.[0-9]{0,2}$/i;
回答by Wouter J
I recommend you to not use REGEX for this, but use a simple !isNaN
:
我建议您不要为此使用 REGEX,而是使用简单的!isNaN
:
console.log(!isNaN('20.13')); // true
console.log(!isNaN('20')); // true
console.log(!isNaN('20kb')); // false
回答by simple-thomas
Try this:
试试这个:
\d+(\.\d{1,2})?
d is for digit d{1,2} is for 1 digit before . and at least 2 digits such as 0.51
d 代表数字 d{1,2} 代表 1 位之前的数字。以及至少 2 位数字,例如 0.51