Tuesday, May 14, 2013

Batch Files GTR and LSS: How to Compare Numbers in Batch Files

Comparing numbers in batch files is not difficult. Usually  you don't need to compare numbers in batch files very often, but sometimes  it is neccessary. What do you need to do to compare two numbers in batch file?
There are two main operators that can help you compare numbers in batch file. They are named GTR and LSS. The first command says whether the first number is greater than the second one, the second command says whether the first number is less than the second one. Here are the examples of their usage:
SET Nmbr1=100
SET Zero=0
IF %Nmbr1% GTR %Zero%   ECHO Greater than zero
Or:
SET Nmbr2=10
SET Hundred=100
IF %Nmbr2% LSS %Hundred%   ECHO Less than one hundred
You can make them nested:
IF %Nmbr2% LSS %Hundred% ( IF %Nmbr1% GTR %Zero% (ECHO  Greater than zero but less than one hundred)
We kindly remind that Dr.Batcher is the best program to create batch file, both .BAT and .CMD, try it if haven't tried it yet. 

1 comment:

  1. The problem I have with comparing numbers is that when they are not the same length the comparison fails. for instance VarA=3 and VarB=20. The IF comparison sees 3 to be greater than 20. ie: IF %VarA% lss %VarB% returns a false result because a string comparison is performed. Is there a way around this other than making the 3 a 03.

    ReplyDelete

Translate