正则表达式强制小数点后两位 [英] Regular expression to enforce 2 digits after decimal point
本文介绍了正则表达式强制小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用JavaScript验证数字字符串,以确保数字恰好有两位小数.
I need to validate a numeric string with JavaScript, to ensure the number has exactly two decimal places.
只有在
- 该数字恰好有两个小数位
- 小数点前至少有一位数字.(可能为零)
- 小数点前的数字不能以多个零开头.
有效号码:
0.01
0.12
111.23
1234.56
012345.67
123.00
0.00
无效的数字:
.12
1.1
0.0
00.00
1234.
1234.567
1234
00123.45
abcd.12
12a4.56
1234.5A
我尝试过正则表达式 [0-9] [\.] [0-9] [0-9] $
,但是它允许小数点前的字母,例如 12a4.56
.
I have tried the regular expression [0-9][\.][0-9][0-9]$
, but it allows letters before decimal point like 12a4.56
.
推荐答案
.
匹配任何字符,它没有按照您认为的方式工作.你必须逃避它.另外,您还有两个错误;尝试
.
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]$
相反,或者甚至更好的是,将 \ d
用作十进制数字:
instead, or even better, use \d
for decimal digits:
^\d+\.\d\d$
这篇关于正则表达式强制小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文