How to check if a parameter (or variable) is a number in a Batch script
Solution 1
SET "var="&for /f "delims=0123456789" %%i in ("%1") do set var=%%i
if defined var (echo %1 NOT numeric) else (echo %1 numeric)
Replace %1
with %yourvarname%
as appropriate
Solution 2
for ± integers
(test also for leading zero):
echo(%~1|findstr "^[-][1-9][0-9]*$ ^[1-9][0-9]*$ ^0$">nul&&echo numeric||echo not numeric
Solution 3
You could try this. The variable passed is for example var
and %var%
is equal to 500
.
set /a varCheck=%var%
if %varCheck% == %var% (goto :confirmed) else (exit /B)
exit /B
:confirmed
:: You can use %var% here, and it should only be executed if it is numerical!
if %var%
is equal to e.g. a3453d
, then it would set varCheck
to be 0
, and because 0
is not equal to a3453d
, then it will exit batch processing.
(The exit on line 3 is just in case the if statement decides not to execute for some reason ... XD.)
Solution 4
The easiest for positive integers should be:
IF 1%1 NEQ +1%1 echo Notnumeric!
If negative numbers (hyphen) are also to be considered, this will work
SET number=%1
if 1%1 EQU +1%1 echo positive number
if %1==-%number:-=% echo negative number
Learned from this article here
Solution 5
@hornzach - You were so close and with a much simpler answer than the rest.
To hide the error message in (win 7 at least) redirect to the standard error output (2) to nul (a special file, that quietly discards the output "bit-bucket")
set /a varCheck = %var% 2>nul
Then the rest of your answer works for the 4 test cases.
Full Answer With Test Cases:
call :CheckNumeric AA "#NOT A VALID NUMBER"
call :CheckNumeric A1 "#NOT A VALID NUMBER"
call :CheckNumeric 1A "#NOT A VALID NUMBER"
call :CheckNumeric 11 "#A VALID NUMBER"
call :CheckNumeric 1.23456789012345678901234567890.123456 "#NOT A VALID NUMBER"
goto :EOF
:CheckNumeric
@ECHO.
@ECHO Test %1
set /a num=%1 2>nul
if {%num%}=={%1} (
@ECHO %1 #A VALID NUMBER, Expected %2
goto :EOF
)
:INVALID
@ECHO %1 #NOT A VALID NUMBER, Expected %2
Outputs:
Test AA
AA #NOT A VALID NUMBER, Expected "#NOT A VALID NUMBER"
Test A1
A1 #NOT A VALID NUMBER, Expected "#NOT A VALID NUMBER"
Test 1A
1A #NOT A VALID NUMBER, Expected "#NOT A VALID NUMBER"
Test 11
11 #A VALID NUMBER, Expected "#A VALID NUMBER"
Test 1.23456789012345678901234567890.123456
1.23456789012345678901234567890.123456 #NOT A VALID NUMBER, Expected "#NOT A VALID NUMBER"
Comments
-
mhshams almost 2 years
I need to check if a parameter that is passed to a Windows Batch file is a numeric value or not. It would be good for the check to also works for variables.
I found an answer to a similar question, where the
findstr
command is used with a regular expression.I did try that solution, but it’s not working like I hoped (at least on Windows 7).
My test scenarios are as follows:
AA # not a valid number A1 # not a valid number 1A # not a valid number 11 # a valid number