2

How does one verify that a variable is a number in a batch file?

1, 2, 4, 5, 10934, 495832945, 4395893428 ->  true
Apple, Orange, Animal, Red, Sky, Leaf -> false
Gray
  • 7,050
  • 2
  • 29
  • 52
Rik Telner
  • 179
  • 1
  • 10

3 Answers3

1
echo %variable%| FINDSTR /R /X " *[0-9]* *" >nul 2>&1 && echo IT IS A NUMBER
echo %variable%| FINDSTR /R /X " *[0-9]* *" >nul 2>&1 || echo IT IS NOT A NUMBER
npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • Good, I found meanwhile new answer, but you deserve answering vote though. I will do it as soon as SO system will allow me to do it (5 mins) – Rik Telner Jul 12 '13 at 14:36
  • Your answer doesn't work properly. After putting non-numbers, numbers doesn't trigger your script anymore. – Rik Telner Jul 12 '13 at 14:41
  • 1
    I've edited the answer.There was an extra space before the first pipe. – npocmaka Jul 12 '13 at 14:45
  • After entered non-number, and then entered a number, it still said that it wasn't number. You have now edited answer, but I have another script, thank you though, and I'll upvote it anyway. – Rik Telner Jul 12 '13 at 14:49
1

Answer found on StackOverflow.com

set /p Input1=Enter number: 
set /a Input2=%Input1% * 1
if "%Input2%"=="0" echo It is not a number.

It doesn't work with 0 to 0.9 numbers.

Rik Telner
  • 179
  • 1
  • 10
1

From http://www.robvanderwoude.com/sourcecode.php?src=isnumber_nt [ Alt Link ]

:: Positive decimal
SET RC=10
FOR /F "tokens=1 delims=0123456789" %%A IN ("%Value%") DO SET RC=0
IF %RC% EQU 10 EXIT /B 10
David Ruhmann
  • 11,064
  • 4
  • 37
  • 47