JavaScript中的正则表达式,用于验证十进制数字 [英] Regex in JavaScript for validating decimal numbers
本文介绍了JavaScript中的正则表达式,用于验证十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要JavaScript中的正则表达式来验证十进制数字.
I want a regex in JavaScript for validating decimal numbers.
它最多只能保留两位小数.例如,它应允许10.89
,但不允许10.899
.
It should allow only up to two decimal places. For example, it should allow 10.89
but not 10.899
.
它还应该只允许一个句点(.
).例如,应允许10.89
,但不允许10.8.9
.
It should also allow only one period (.
). For example, it should allow 10.89
but not 10.8.9
.
推荐答案
尝试以下表达式:^\d+\.\d{0,2}$
如果希望小数位是可选的,则可以使用以下内容:^\d+(\.\d{1,2})?$
Try the following expression: ^\d+\.\d{0,2}$
If you want the decimal places to be optional, you can use the following: ^\d+(\.\d{1,2})?$
编辑:要在Javascript中测试字符串匹配,请使用以下代码段:
To test a string match in Javascript use the following snippet:
var regexp = /^\d+\.\d{0,2}$/;
// returns true
regexp.test('10.5')
这篇关于JavaScript中的正则表达式,用于验证十进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文