Skip to main content

How to Check if a String is a Valid Number in Batch Script

In interactive scripts or data processing, it's crucial to validate your input. Before you can perform mathematical operations, you need to ensure that a given value is actually a number. Attempting to use a non-numeric string in a calculation will cause your script to fail. Since batch scripting has no built-in IsNumeric() function, we must use a clever workaround to perform this validation.

This guide will teach you the two most effective methods for checking if a string is a valid integer. We will cover the simple and fast "pure-batch" method using the SET /A command, and the more flexible and powerful method using FINDSTR with regular expressions.

The Core Method: The SET /A Command Trick

This is the most common and "batch-native" way to check if a string is a valid 32-bit signed integer. The SET /A command is the arithmetic evaluator in batch. We can exploit its behavior to test a string.

The logic behind the attempt to use the string in a simple math operation is the following:

  • If the string is a valid number (e.g., "123", "-50"), the operation succeeds, and %ERRORLEVEL% is set to 0.
  • If the string contains any non-numeric characters (e.g., "123a", "abc"), the operation fails, and %ERRORLEVEL% is set to a non-zero value.
@ECHO OFF
SET "INPUT_STRING=12345"

REM The '2>NUL' suppresses the "Invalid number" error message.
SET /A "result = %INPUT_STRING% + 0" 2>NUL

IF %ERRORLEVEL% EQU 0 (
ECHO The string "%INPUT_STRING%" is a valid integer.
) ELSE (
ECHO The string "%INPUT_STRING%" is NOT a valid integer.
)

An Alternative Method: Using FINDSTR with Regular Expressions

For more complex validation, FINDSTR is a more powerful tool. We can use a regular expression to define exactly what a "valid number" looks like. This method is more flexible but also more complex.

An alternative logic is the one in which we ECHO the string and pipe it to FINDSTR, which checks if the entire string matches our number pattern.

  • FINDSTR /R "^[0-9]*$": This checks for a string that contains only digits.
    • /R: Use Regular expression search.
    • ^: Matches the beginning of the line.
    • [0-9]*: Matches any character from 0 to 9, zero or more times.
    • $: Matches the end of the line.

FINDSTR sets %ERRORLEVEL% to 0 for a match and 1 for no match.

@ECHO OFF
SET "INPUT_STRING=12345"

ECHO "%INPUT_STRING%" | FINDSTR /R "^[0-9]*$" > NUL

IF %ERRORLEVEL% EQU 0 (
ECHO The string is a valid non-negative integer.
) ELSE (
ECHO The string is NOT a valid non-negative integer.
)

Basic Example: Validating a String

Let's test both methods with a valid and an invalid string.

Input String: 500

  • SET /A Result: Is a valid integer.
  • FINDSTR Result: Is a valid non-negative integer.

Input String: 500x

  • SET /A Result: Is NOT a valid integer.
  • FINDSTR Result: Is NOT a valid non-negative integer.

How the SET /A Trick Works

The command SET /A "result = %INPUT_STRING% + 0" forces the batch arithmetic parser to evaluate the input. It doesn't change the value, but it serves as a test. If %INPUT_STRING% is "abc", the parser cannot compute "abc" + 0, so it fails and sets a non-zero ERRORLEVEL. If the string is "500", it computes 500 + 0, succeeds, and sets %ERRORLEVEL% to 0.

Handling Negative Numbers and Zero

  • SET /A: This method handles negative integers (-10) and zero (0) flawlessly by default. It is its main advantage.
  • FINDSTR: The simple regex ^[0-9]*$ will fail on negative numbers. You must modify it to optionally allow a leading hyphen.

The following FINDSTR script is for positive and negative integers:

@ECHO OFF
SET "INPUT_STRING=-50"

REM The '-' is optional at the start.
ECHO "%INPUT_STRING%" | FINDSTR /R "^-*[0-9][0-9]*$" > NUL

IF %ERRORLEVEL% EQU 0 (
ECHO The string is a valid integer (positive or negative).
) ELSE (
ECHO The string is NOT a valid integer.
)

Common Pitfalls and How to Solve Them

Problem: SET /A Prints an Error Message

When the SET /A command fails, it prints an error to the console.

When the error occurs we get:

Invalid number.  Numeric constants are either decimal (17),
hexadecimal (0x11), or octal (021).

Solution: Redirect Error Output to NUL

You can suppress this message by redirecting the standard error stream (stream 2) to the null device (NUL). This keeps your script's output clean.

SET /A "result = %INPUT_STRING% + 0" 2>NUL

Problem: Handling Decimals (Floating-Point Numbers)

Neither of these methods works for decimals.

  • SET /A only supports 32-bit signed integers. It will fail on 12.34.
  • The FINDSTR regex would need to be made much more complex to correctly handle decimals (12.34, .5, 10.).

Solution: For any validation involving floating-point numbers, the best and most reliable tool is PowerShell.

@ECHO OFF
SET "INPUT_STRING=12.34"
powershell -Command "try { [double]::Parse('%INPUT_STRING%') | Out-Null; exit 0 } catch { exit 1 }"
IF %ERRORLEVEL% EQU 0 (ECHO Is a valid number) ELSE (ECHO Is NOT a valid number)

Practical Example: A User Input Validation Loop

This is a classic use case. The script asks the user for their age and will not continue until they enter a valid, non-negative integer.

@ECHO OFF
SETLOCAL

:Prompt
SET "UserAge="
SET /P "UserAge=Please enter your age: "

REM --- Validation Step ---
ECHO "%UserAge%" | FINDSTR /R "^[0-9][0-9]*$" > NUL
IF %ERRORLEVEL% EQU 0 (
ECHO Thank you. You entered the number: %UserAge%
GOTO :End
)

ECHO.
ECHO [ERROR] Invalid input. Please enter numbers only.
ECHO.
GOTO :Prompt

:End
ENDLOCAL

Conclusion

Validating numeric input is essential for creating robust batch scripts.

  • The SET /A trick is the quickest and easiest method for validating integers (positive and negative). Remember to use 2>NUL to suppress errors.
  • The FINDSTR method is more flexible and powerful, allowing you to use regular expressions to define exactly what patterns are acceptable (e.g., only positive integers, numbers of a specific length).
  • For decimals or any complex validation, leveraging a PowerShell one-liner is the most reliable and modern solution.