can a batch tell if a number is bigger or smaller than anoth

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
BatMaster
Posts: 28
Joined: 22 Dec 2010 12:53

can a batch tell if a number is bigger or smaller than anoth

#1 Post by BatMaster » 18 Aug 2011 16:19

Can a batch file tell if a number is bigger or smaller than another number
the reason i need to find this out is for high scores on a batch file game
the batch file stores the high score in a text file
reads the text file when ever the file is run
the batch file ovewrites the score wether its higher or lower
any suggestions? any help will be greatly appreciated.
thanks in advance--=BatMaster=--

Batcher
Posts: 74
Joined: 16 Apr 2009 10:36

Re: can a batch tell if a number is bigger or smaller than a

#2 Post by Batcher » 19 Aug 2011 00:35

Code: Select all

@echo off
set n1=3
set n2=5
if %n1% lss %n2% (
    echo smaller
) else if %n1% gtr %n2% (
    echo bigger
) else if %n1% equ %n2% (
    echo equal
)
pause

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: can a batch tell if a number is bigger or smaller than a

#3 Post by dbenham » 19 Aug 2011 05:55

More importantly - this works

Code: Select all

set score=10
set hiScore=9
if %score% gtr %hiScore% (
  set hiScore=%score%
  echo New high score = %hiScore%
)
because IF sorts the values as numeric values as long as they contain nothing but digits.

If either value contains at least one character that is not a digit then the values are sorted alphabetically instead:
For example, 9 would be greater than 10x

Dave Benham

BatMaster
Posts: 28
Joined: 22 Dec 2010 12:53

Re: can a batch tell if a number is bigger or smaller than a

#4 Post by BatMaster » 19 Aug 2011 07:39

@dbenham your cose doesnt change the value of hiscore even if score=123 and hiscore=9
@batcher your code works perfectly i wil pm you the code for the game soon
regards--=BatMaster=--

BatMaster
Posts: 28
Joined: 22 Dec 2010 12:53

Re: can a batch tell if a number is bigger or smaller than a

#5 Post by BatMaster » 19 Aug 2011 07:58

@dbenham
i fixed your code

Code: Select all

@echo off &setlocal
set score=10
set hiScore=9
if %score% lss %hiScore% goto end
set hiScore=%score%
echo New high score = %hiScore%
pause
:end
exit

--=BatMaster=--

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: can a batch tell if a number is bigger or smaller than a

#6 Post by dbenham » 19 Aug 2011 08:41

Thanks! I made a rookie mistake. You can't see changes to variables within a loop using immediate expansion :oops:

My code would work fine if I used delayed expansion:

Code: Select all

setlocal enableDelayedExpansion
set score=10
set hiScore=9
if %score% gtr %hiScore% (
  set hiScore=!score!
  echo New high score = !hiScore!
)

Your fix to my code is also a good solution

Dave Benham

Post Reply