Last Updated on 2022-06-04 by Clay
When we building a webpage, sometimes we need to allow users to key in some numbers. But at this time, maybe we need to use some rules to determine the string users key in is a valid number.
The following are some classic methods:
isNaN()
parseFloat()
isNaN()
NaN means Not a Number, if isNaN()
return false means the string is a valid number.
This method is useful but have a problem: it return false if it get null or space.
// Init
var num_01 = "100";
var num_02 = "a33";
var num_03 = " ";
var num_04 = "";
// Determined
console.log("100:", isNaN(num_01));
console.log("a33:", isNaN(num_02));
console.log("' ':", isNaN(num_03));
console.log("'':", isNaN(num_04));
Output:
100: false
a33: true
' ': false
'': false
parseFloat()
When parseFloat()
judges a string that is not a number, it will return it as NaN. We can write a judgment function based on this feature.
(Note: The function I wrote returns true to represent a number, which is just the opposite of isNaN()
above)
// Init
var num_01 = "100";
var num_02 = "a33";
var num_03 = " ";
var num_04 = "";
// isNumber
function isNumber(inputs) {
return parseFloat(inputs).toString() != "NaN";
}
// Determined
console.log("100:", isNumber(num_01));
console.log("a33:", isNumber(num_02));
console.log("' ':", isNumber(num_03));
console.log("'':", isNumber(num_04));
Output:
100: true
a33: false
' ': false
'': false
References
- https://www.w3schools.com/jsref/jsref_isnan.asp
- https://mkyong.com/javascript/check-if-variable-is-a-number-in-javascript/