我需要JavaScript中的正则表达式,它只接受以.5或.0结尾的正数和小数。
(^\d*\.?\d*[1-9]+\d*$)|(^[1-9]+\d*\.\d*$)
这就是我所拥有的,但我不知道如何将其更改为拒绝0和0.0,并拒绝以.1 .2 .3 .4 .6 .7 .8 .9 .9
结尾的那些Accept:
0.5
1.0
1.5
2.0
2.5
3.0
1
2
3
4
但是
Reject:
-1.0
-0.5
-0.0
-0.1
-0.7
0
0.0
0.1
0.9
0.4
1.3
1.11
1.51
2.01
答案 0 :(得分:4)
将数字乘以2并查看它是否为整数:
function check(v) {
return v > 0 && !(v*2 % 1);
}
var tests = [
0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 1, 2, 3, 4,
-1.0, -0.5, -0.0, -0.1, -0.7, 0.0, 0.1, 0.9, 0.4, 1.3, 1.11, 1.51, 2.01];
tests.forEach(v => console.log(v, check(v) ? "passes": "fails"));
答案 1 :(得分:3)
答案 2 :(得分:0)
以下正则表达式如何:^\d*\.\d{0,}(0|5)
?
以下是解释:
^ //line start
\d* //any number (or none) occurrences of any number
\. //decimal dot
\d{0,} //0 or more digits (actually the same as * - you can use it here too)
(0|5) //ends with 0 or 5
答案 3 :(得分:0)
试一试:
<html>
<head>
</head>
<body>
<script>
var patt = /^(\+)?\d+(\.[05])?$/;
var number = 1.5;
if (number > 0 && patt.test(number))
alert("Number is valid");
else
alert("Number is Invalid");
</script>
</body>
</html>