Checking for Floating point numbers
A floating number has the following parts.
- A decimal integer.
- A decimal point ('.').
- A fraction.
- An exponent (optional).
The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-").
Example of some floating numbers:
- 7.2935
- -12.72
- 1/2
- 12.4e3 [ Equivalent to 12.4 x 103 ]
- 4E-3 [ Equivalent to 4 x 10-3 ]
Sometimes it is required to input a number with decimal part particularly for quantity, length, height, amounts etc. We can use a floating point number in various ways, here are some examples.
- No exponent, mandatory integer and fraction and optional sign.
- No exponent, mandatory sign (+-), integer, and a fraction.
- Mandatory sign (+-), exponent, integer, fraction.
To check the said format we have used the various regular expression. Following code blocks contain actual codes and we have kept the CSS code part common for all the validations.
CSS Code
Javascript function to check whether a field input contains a number with no exponent, mandatory integer and fraction and optional sign
To get a string contains a number with no exponent, mandatory integer and fraction and optional sign we use a regular expression /^[-+]?[0-9]+\.[0-9]+$/ which allows the said format. Next, the match() method of a string object is used to match the said regular expression against the input value. Here is the complete web document.
HTML Code
JavaScript Code
Flowchart :
Javascript function to check whether a field input contains a number with no exponent, mandatory sign (+-), integer, and fraction
To get a string contains a number with no exponent, mandatory integer, fraction, sign (+ -) we use a regular expression /[-+][0-9]+\.[0-9]+$/ which allows the said format. Next, the match() method of a string object is used to match the said regular expression against the input value. Here is the complete web document.
HTML Code
JavaScript Code
Flowchart:
Javascript function to check whether a field input contains a number starting with mandatory sign (+-), exponent, integer, fraction
To get a string contains a number with a mandatory sign (+ -), exponent integer, fraction, a sign we use a regular expression /^[-+][0-9]+\.[0-9]+[eE][-+]?[0-9]+$/ which allows the said format. Next, the match() method of a string object is used to match the said regular expression against the input value. Here is the complete web document.
HTML Code
JavaScript Code
Flowchart:
No comments:
Post a Comment