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
.
To validate decimal numbers in JavaScript, use the match() method. It retrieves the matches when matching a string against a regular expression.
JavaScript Code:function number_test(n) { var result = (n - Math. floor(n)) !== 0; if (result) return 'Number has a decimal place. '; else return 'It is a whole number.
A regular expression for a decimal number needs to checks for one or more numeric characters (0-9) at the start of the string, followed by an optional period, and then followed by zero or more numeric characters (0-9). This should all be followed by an optional plus or minus sign.
The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).
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')
/^\d+(\.\d{1,2})?$/
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'));
/ /
: 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 testingYou can use regexr.com or regex101.com for testing regular expressions directly in the browser!
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