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);
};
Try something like this:
^\d+\.\d{0,3}$
where "3" is the maximum allowed decimal places.
/^\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*$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With