How to check if a parameter (or variable) is a number in a Batch script

后端 未结 10 571
南方客
南方客 2020-12-01 08:02

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 a

10条回答
  •  臣服心动
    2020-12-01 08:47

    Does the same thing as above. Have problems with special characters. However, the solution is of a different approach.

    @echo off
    cls
    setlocal enabledelayedexpansion
    
    if "%1"=="" (goto:eof) else (set _VAR2CHECK=%1)
    
    for /l %%a in (0,1,9) do (
       if defined _VAR2CHECK (set "_VAR2CHECK=!_VAR2CHECK:%%a=!") else (goto :end)
    )
    
    :end
    if defined _VAR2CHECK (echo %1 #NOT A VALID NUMBER) else (echo %1 #A VALID NUMBER)
    
    set "_VAR2CHECK="
    endlocal
    

    Test scenarions:

    C:\>ISNUM 1A
    1A  #NOT A VALID NUMBER
    
    C:\>ISNUM 11
    11  #A VALID NUMBER
    

提交回复
热议问题