admin管理员组文章数量:1186450
I need to validate a numeric string with JavaScript, to ensure the number has exactly two decimal places.
The validation will pass only if
- the number has precisely two decimal places
- there is at least one digit before the decimal point. (could be zero)
- the number before the decimal point can not begin with more than one zero.
Valid numbers:
0.01
0.12
111.23
1234.56
012345.67
123.00
0.00
Invalid numbers:
.12
1.1
0.0
00.00
1234.
1234.567
1234
00123.45
abcd.12
12a4.56
1234.5A
I have tried the regular expression [0-9][\.][0-9][0-9]$
, but it allows letters before decimal point like 12a4.56
.
I need to validate a numeric string with JavaScript, to ensure the number has exactly two decimal places.
The validation will pass only if
- the number has precisely two decimal places
- there is at least one digit before the decimal point. (could be zero)
- the number before the decimal point can not begin with more than one zero.
Valid numbers:
0.01
0.12
111.23
1234.56
012345.67
123.00
0.00
Invalid numbers:
.12
1.1
0.0
00.00
1234.
1234.567
1234
00123.45
abcd.12
12a4.56
1234.5A
I have tried the regular expression [0-9][\.][0-9][0-9]$
, but it allows letters before decimal point like 12a4.56
.
7 Answers
Reset to default 8.
matches any character, it does not do what you think it does. You have to escape it. Also, you have two more errors; try
^[0-9]+\.[0-9][0-9]$
instead, or even better, use \d
for decimal digits:
^\d+\.\d\d$
This covers all requirements:
^(0|0?[1-9]\d*)\.\d\d$
- the number has precisely two decimal places
- Trivially satisfied due to the non-optional
\.\d\d$
- Trivially satisfied due to the non-optional
The other two conditions can be restated as follows:
- The number before the decimal points is either a zero
- or a number with exactly one zero, then a number that does not start with zero
This is covered in these two cases:
0
0?[1-9]\d*
You don't need regular expressions for this.
JavaScript has a function toFixed()
that will do what you need.
var fixedtotwodecimals = floatvalue.toFixed(2);
i used this
^[1-9][1-9]*[.]?[1-9]{0,2}$
0 not accept
123.12 accept but 123.123 not accept
1 accept
12213123 accept
sdfsf not accept
15.12 accept
15@12 not accept
15&12 not accept
var values='0.12';
document.write(values.match(/\d+[.]+\d+\d/));
change value as you want and check it
Here it is:
^(0[.]+\d{2})|^[1-9]\d+[.]+\d{2}$
Try This Code
pattern="[0-9]*(\.?[0-9]{1,2}$)?"
1 Valid
1.1 Valid
1.12 Valid
1.123 not Valid
only number Valid
pattern="[0-9]*(.?[0-9]{2}$)?"
1 Valid
1.1 not Valid
1.12 Valid
1.123 not Valid
only number Valid
本文标签: javascriptRegular expression to enforce 2 digits after decimal pointStack Overflow
版权声明:本文标题:javascript - Regular expression to enforce 2 digits after decimal point - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738281046a2072726.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论