gunakkoc
gunakkoc

Reputation: 1069

How to compare string to an integer?

I have this:

@echo off
setlocal ENABLEDELAYEDEXPANSION
set bla="-666"
set zzz="333"
if !zzz! LSS !bla! echo lesser
pause

Gives me "lesser" which is wrong. I know this is because of the ASCII values. But what is the way around to compare them as if they are numbers?

EDIT:

Some more codes:

set mn=99999
for /f "tokens=1-9" %%a in (%%g) do (
set zzz=%%d
)
if "!zzz!" LSS "!mn!" set mn=!zzz!

None of the answers below gave me the correct result so far...

Upvotes: 2

Views: 1004

Answers (3)

Ofir Luzon
Ofir Luzon

Reputation: 10908

This works for me, removing the quotes and then comparing.

@echo off
setlocal ENABLEDELAYEDEXPANSION
set bla="-666"
set zzz="333"
for %%a in (!bla!) do set /a bla=%%~a+0
for %%a in (!zzz!) do set /a zzz=%%~a+0
echo !bla! !zzz!
if !bla! LSS !zzz! (
    echo lesser
) else (
    echo greater
)   
pause

Upvotes: 0

Bali C
Bali C

Reputation: 31221

This works for me

@echo off
set bla=-666
set zzz=333
if %zzz% LSS %bla% echo lesser
pause >nul

No need for quotes or delayed expansion.

Upvotes: 2

ElektroStudios
ElektroStudios

Reputation: 20464

You are taking incorrect use of the blackquotes when setting a var, the VAR="CONTENT" are only for special cases, but not this.

@echo off
set /A "bla=-666"
set /A "zzz=333"
if %zzz% LSS %bla% echo lesser
pause

Notice i've used blackquotes to enclose the variable, the content don't have any blackquote.

And remember too to NOT use blackquotes in the comparision when comparing numbers, like this:

if "%zzz%" LSS "%bla%" echo lesser

Upvotes: 0

Related Questions