Regex in JavaScript for validating decimal numbers
I want a regex in JavaScript for validating decimal numbers.
It should allow only up to two decimal places. For example, it should allow 10.89
but not 10.899
.
It should also allow only one period (.
). For example, it should allow 10.89
but not 10.8.9
.
Solution 1:
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})?$
EDIT: To test a string match in Javascript use the following snippet:
var regexp = /^\d+\.\d{0,2}$/;
// returns true
regexp.test('10.5')
Solution 2:
Regex
/^\d+(\.\d{1,2})?$/
Demo
var regexp = /^\d+(\.\d{1,2})?$/;
console.log("'.74' returns " + regexp.test('.74'));
console.log("'7' returns " + regexp.test('7'));
console.log("'10.5' returns " + regexp.test('10.5'));
console.log("'115.25' returns " + regexp.test('115.25'));
console.log("'1535.803' returns " + regexp.test('1535.803'));
console.log("'153.14.5' returns " + regexp.test('153.14.5'));
console.log("'415351108140' returns " + regexp.test('415351108140'));
console.log("'415351108140.5' returns " + regexp.test('415351108140.5'));
console.log("'415351108140.55' returns " + regexp.test('415351108140.55'));
console.log("'415351108140.556' returns " + regexp.test('415351108140.556'));
Explanation
-
/ /
: the beginning and end of the expression -
^
: whatever follows should be at the beginning of the string you're testing -
\d+
: there should be at least one digit -
( )?
: this part is optional -
\.
: here goes a dot -
\d{1,2}
: there should be between one and two digits here -
$
: whatever precedes this should be at the end of the string you're testing
Tip
You can use regexr.com or regex101.com for testing regular expressions directly in the browser!