Search code examples
windowsbatch-fileif-statementcmdcomparison

Wrong output when comparing 2 numbers in batch


I am testing something with a batch file to compare 2 numbers if greater, less or equal. I start making this test to find out why my other script that requires a comparison between 2 numbers and did not work properly. During the test I found the issue and I cannot understand why it's happening. I hope you can help me with this one.

Let's say I have 2 variables:

set a=12.5
set b=10.0

if I compare those 2 numbers:

IF %A% GTR %B% (echo A greater than B) ELSE (IF %A% LSS %B% (echo B greater than A) ELSE (echo A equal B))

The output is: A greater than B

I tested multiple numbers with decimals and works just fine, EXCEPT when one number is less than 10 and the other number is higher than 10.

example:

set a=9.9
set b=12.3

IF %A% GTR %B% (echo A greater than B) ELSE (IF %A% LSS %B% (echo B greater than A) ELSE (echo A equal B))

in this case the output is: A greater than B which is wrong.

Anyone can explain me why is this happening and how to fix this?


Solution

  • Run if /? and you'll see that

    These comparisons are generic, in that if both string1 and string2 are both comprised of all numeric digits, then the strings are converted to numbers and a numeric comparison is performed.

    Since decimal numbers like 12.5, 10.0, 9.9... are not comprised of all numeric digits (they contain the . character), they'll be left as strings and will be compared lexicographically just like the default string comparison in any languages. Since 9 is larger than 1, "9.9" is sorted after "10.0"

    In fact just compare any numbers whose number of digits differ and you'll see the same phenomenon. For example 123.5 will be "smaller" than 34.2

    To compare numbers lexicographic order they need to have the same width, which means you must pad zeros before and after the numbers so that the lengths before and after the radix point are the same, for example "112.400" and "009.987"

    For more information read