Skip to content

[JavaScript] How to Determine a String a a Valid Number

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


Read More

Leave a ReplyCancel reply

Exit mobile version