How to Check If String Input Is a Number

How to check if string input is a number?

Simply try converting it to an int and then bailing out if it doesn't work.

try:
val = int(userInput)
except ValueError:
print("That's not an int!")

See Handling Exceptions in the official tutorial.

How to check if the input string is an integer

To check if the input string is numeric, you can use this:

s = input()
if s.isnumeric() or (s.startswith('-') and s[1:].isdigit()):
print('mission successful!')
else:
print('mission failed!')

In Python, checking if a string equals a number will always return False. In order to compare strings and numbers, it helps to either convert the string to a number or the number to a string first. For example:

>>> "1" == 1
False
>>> int("1") == 1
True

or

>>> 1 == "1"
False
>>> str(1) == "1"
True

If a string can not be converted to a number with int, a ValueError will be thrown. You can catch it like this:

try:
int("asdf")
except ValueError:
print("asdf is not an integer")

How do I check if an input is an integer or not in python?

You could try to convert the input to integer with try/except:

user_number = input()

try:
int(user_number)
except:
print("That's not an integer number.")

Identify if a string is a number

int n;
bool isNumeric = int.TryParse("123", out n);

Update As of C# 7:

var isNumeric = int.TryParse("123", out int n);

or if you don't need the number you can discard the out parameter

var isNumeric = int.TryParse("123", out _);

The var s can be replaced by their respective types!

How do I check if a string is a number (float)?

Which, not only is ugly and slow

I'd dispute both.

A regex or other string parsing method would be uglier and slower.

I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

The issue is that any numeric conversion function has two kinds of results

  • A number, if the number is valid
  • A status code (e.g., via errno) or exception to show that no valid number could be parsed.

C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

I think your code for doing this is perfect.

How to check If the value of an input is number or string in react js?

The simplest way will be to convert the string to a number and then check if its valid. As the value of inputs is always a string even if u use type="number", tho it is good to use it if u just want numbers as the input.

You can use isNaN(+value). Here + will convert a string to a number.

<input
type="text"
onChange={(e) => {
const value = e.target.value;
console.log(!isNaN(+value)); // true if its a number, false if not
}}
/>;

Some test cases:

console.log(!isNaN(+"54"));
console.log(!isNaN(+"23xede"));
console.log(!isNaN(+"test"));

How to check if a String is numeric in Java

With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.

With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric.

You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.isParsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)

How can I check if a string is a valid number?

2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point ".":

function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}


To check if a variable (including a string) is a number, check if it is not a number:

This works regardless of whether the variable content is a string or number.

isNaN(num)         // returns true if the variable does NOT contain a valid number

Examples

isNaN(123)         // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
isNaN('') // false
isNaN(' ') // false
isNaN(false) // false

Of course, you can negate this if you need to. For example, to implement the IsNumeric example you gave:

function isNumeric(num){
return !isNaN(num)
}

To convert a string containing a number into a number:

Only works if the string only contains numeric characters, else it returns NaN.

+num               // returns the numeric value of the string, or NaN 
// if the string isn't purely numeric characters

Examples

+'12'              // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN

To convert a string loosely to a number

Useful for converting '12px' to 12, for example:

parseInt(num)      // extracts a numeric value from the 
// start of the string, or NaN.

Examples

parseInt('12')     // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last three may
parseInt('12a5') // 12 be different from what
parseInt('0x10') // 16 you expected to see.

Floats

Bear in mind that, unlike +num, parseInt (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt() because of this behaviour, you're probably better off using another method instead):

+'12.345'          // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12

Empty strings

Empty strings may be a little counter-intuitive. +num converts empty strings or strings with spaces to zero, and isNaN() assumes the same:

+''                // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false

But parseInt() does not agree:

parseInt('')       // NaN
parseInt(' ') // NaN

How to check if user input is a string

A string with a number in it is still a valid string - it's a string representing that number as text.

If you want to check that the name is not a string composed just of digits, then the following code will work:

while True:
try:
name = input('Insert name: ')
if name.isdigit():
raise ValueError


Related Topics



Leave a reply



Submit