[Solved-6 Solutions] Validate decimal numbers - javascript tutorial
Problem:
How to validate decimal numbers in JavaScript ?
Solution 1:
match() method retrieves the matches when matching a string against a regular expression
To Validate Decimal numbers, we can use the following code:
Solution 2:
To implement an IsNumeric function, to find out if a variable contains a numeric value, regardless of its type, it can be a String containing a numeric, a Number object, virtually anything can be passed to that function.
We couldn't make any type assumptions, taking care of type coercion (eg. +true == 1; but true shouldn't be considered as "numeric").
Solution 3:
- RegEx is easy to make subtle, impossible to spot mistakes with your regular expression.
- If we can't use isNaN(), this should work fine:
- The (input - 0) expression forces JavaScript to do type coercion on your input value, it must first be taken as a number for the subtraction operation.
- If that conversion to a number fails, the expression will result in NaN. This numeric result is then compared to the original value you passed in.
- Since the left-hand side is numeric, type coercion is again used. Now that the input from both sides was coerced to the same type from the same original value, you would think they should always be the same (always true).
- However, NaN is never equal to NaN, so that value can't be converted to a number (and only values that cannot be converted to numbers) will result in false.
- The check on the length is for a special case involving empty strings.
- Note that it falls down on your 0x89f test, but that's in many environments that's an easy way to define a number literal. If we need to catch that specific scenario we can add an additional check.
Solution 4:
This solution works fine
- And to test it:
Try this Regex:
Solution 5:
This works for 0x23 type numbers.
Solution 6:
Use this code: