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

后端 未结 10 572
南方客
南方客 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:54

    @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"
    

提交回复
热议问题