本文介绍了正则表达式,最多可匹配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个小数位的数字
发布评论