正则表达式,最多可匹配2个小数位的数字

编程入门 行业动态 更新时间:2024-10-27 20:34:22
本文介绍了正则表达式,最多可匹配2个小数位的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一个正则表达式,它将匹配数字值和最多用户定义的小数位数.目前我有

I am after a regex that will match numeric values with up to a user defined number of decimal places. Currently I have

/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/

这将允许输入尽可能多的位置,但我也想有时允许2表示货币或4或更多表示其他输入.我正在构建的功能是

which will allow as many places as input but I would also like to sometimes allow 2 for currency or 4 or more for other input. The function I am building is

var isNumeric = function(val, decimals) { // decimals is not used yet var objRegExp = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/; return objRegExp.test(val); };

推荐答案

/^\s*-?[1-9]\d*(\.\d{1,2})?\s*$/

宽恕空格(\ s)是很好的.以上不允许从零开始.如果要允许的话:

It's good to be forgiving of whitespace (\s). The above doesn't allow starting with zero. If you want to allow that:

/^\s*-?\d+(\.\d{1,2})?\s*$/

以上两种方法均不允许小数点后没有小数点.如果要允许的话:

Neither of the above allow a decimal number with nothing before the decimal place. If you want to allow that:

/^\s*-?(\d+(\.\d{1,2})?|\.\d{1,2})\s*$/

更多推荐

正则表达式,最多可匹配2个小数位的数字

本文发布于:2023-11-10 23:02:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576703.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数位   最多   数字   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!