parseFloat()
to try to convert n
to a number.!Number.isNaN()
to check if num
is a number.Number.isFinite()
to check if num
is finite.Number()
and the loose equality operator (==
) to check if the coercion holds.const validateNumber = n => {
const num = parseFloat(n);
return !Number.isNaN(num) && Number.isFinite(num) && Number(n) == n;
}
validateNumber('10'); // true
validateNumber('a'); // false
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️