Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that matches numeric with up to 2 decimal places

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*$)/

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);
};
like image 768
Craig Avatar asked Mar 19 '09 00:03

Craig


2 Answers

Try something like this:

^\d+\.\d{0,3}$

where "3" is the maximum allowed decimal places.

like image 162
Andrew Hare Avatar answered Oct 26 '22 03:10

Andrew Hare


/^\s*-?[1-9]\d*(\.\d{1,2})?\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*$/
like image 42
cletus Avatar answered Oct 26 '22 04:10

cletus