The most efficient way to check if a string is an integer in Python is to use the str. isdigit() method, as it takes the least time to execute. The str. isdigit() method returns True if the string represents an integer, otherwise False .
We can use the isdigit() function to check if the string is an integer or not in Python. The isdigit() method returns True if all characters in a string are digits. Otherwise, it returns False.
You need to first check if it's a number. If so you can use the Math. Round method. If the result and the original value are equal then it's an integer.
Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.
[[ $var =~ ^-?[0-9]+$ ]]
^
indicates the beginning of the input pattern-
is a literal "-"?
means "0 or 1 of the preceding (-
)"+
means "1 or more of the preceding ([0-9]
)"$
indicates the end of the input patternSo the regex matches an optional -
(for the case of negative numbers), followed by one or more decimal digits.
References:
Wow... there are so many good solutions here!! Of all the solutions above, I agree with @nortally that using the -eq
one liner is the coolest.
I am running GNU bash, version 4.1.5
(Debian). I have also checked this on ksh (SunSO 5.10).
Here is my version of checking if $1
is an integer or not:
if [ "$1" -eq "$1" ] 2>/dev/null
then
echo "$1 is an integer !!"
else
echo "ERROR: first parameter must be an integer."
echo $USAGE
exit 1
fi
This approach also accounts for negative numbers, which some of the other solutions will have a faulty negative result, and it will allow a prefix of "+" (e.g. +30) which obviously is an integer.
Results:
$ int_check.sh 123
123 is an integer !!
$ int_check.sh 123+
ERROR: first parameter must be an integer.
$ int_check.sh -123
-123 is an integer !!
$ int_check.sh +30
+30 is an integer !!
$ int_check.sh -123c
ERROR: first parameter must be an integer.
$ int_check.sh 123c
ERROR: first parameter must be an integer.
$ int_check.sh c123
ERROR: first parameter must be an integer.
The solution provided by Ignacio Vazquez-Abrams was also very neat (if you like regex) after it was explained. However, it does not handle positive numbers with the +
prefix, but it can easily be fixed as below:
[[ $var =~ ^[-+]?[0-9]+$ ]]
Latecomer to the party here. I'm extremely surprised none of the answers mention the simplest, fastest, most portable solution; the case
statement.
case ${variable#[-+]} in
*[!0-9]* | '') echo Not a number ;;
* ) echo Valid number ;;
esac
The trimming of any sign before the comparison feels like a bit of a hack, but that makes the expression for the case statement so much simpler.
I like the solution using the -eq
test, because it's basically a one-liner.
My own solution was to use parameter expansion to throw away all the numerals and see if there was anything left. (I'm still using 3.0, haven't used [[
or expr
before, but glad to meet them.)
if [ "${INPUT_STRING//[0-9]}" = "" ]; then
# yes, natural number
else
# no, has non-numeral chars
fi
For portability to pre-Bash 3.1 (when the =~
test was introduced), use expr
.
if expr "$string" : '-\?[0-9]\+$' >/dev/null
then
echo "String is a valid integer."
else
echo "String is not a valid integer."
fi
expr STRING : REGEX
searches for REGEX anchored at the start of STRING, echoing the first group (or length of match, if none) and returning success/failure. This is old regex syntax, hence the excess \
. -\?
means "maybe -
", [0-9]\+
means "one or more digits", and $
means "end of string".
Bash also supports extended globs, though I don't recall from which version onwards.
shopt -s extglob
case "$string" of
@(-|)[0-9]*([0-9]))
echo "String is a valid integer." ;;
*)
echo "String is not a valid integer." ;;
esac
# equivalently, [[ $string = @(-|)[0-9]*([0-9])) ]]
@(-|)
means "-
or nothing", [0-9]
means "digit", and *([0-9])
means "zero or more digits".
Here's yet another take on it (only using the test builtin command and its return code):
function is_int() { test "$@" -eq "$@" 2> /dev/null; }
input="-123"
if is_int "$input"
then
echo "Input: ${input}"
echo "Integer: ${input}"
else
echo "Not an integer: ${input}"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With