CMD set /a, modulus, and negative numbers

14,397

Solution 1

The % in CMD much like in other microsoft environments is a remainder function - not a true modulo operation. The remainder is accurate here to return -6 for your examples. Using mod in Excel is a true modulo which does return your expected 1.

Although it's written for C#, the article below has a great breakdown of the difference: http://blogs.msdn.com/b/ericlippert/archive/2011/12/05/what-s-the-difference-remainder-vs-modulus.aspx

Solution 2

If you want true modulo, than you can use this:

set a=-90
set b=7
set /a (a%b+b)%b

Solution 3

As Jason W said, % isn't a modulo operator. But if you want -b mod N, maybe this can help:

@echo off
set /a num1=7
set /a num2=-90
:add
if %num2% LSS 0 set /a num2+=num1&goto add
echo/%num2%
pause
Share:
14,397
unclemeat
Author by

unclemeat

IT apprentice; currently working in networking, previously working in virtualization.

Updated on June 25, 2022

Comments

  • unclemeat
    unclemeat over 1 year

    Is CMD unable to evaluate the modulus of negative numbers using set /a?

    90 % 7 correctly equates to 6 in batch, however -90 % 7 gives -6 instead of 1.

    I thought that it might have been evaluating -(90 % 7), but this doesn't seem to be the case as (-90) % 7 also gives -6.

    h:\uprof>set /a -90%7
    -6
    h:\uprof>set /a (-90)%7
    -6
    

    So - is this a limitation of CMDs set /a Modulus operator?

  • unclemeat
    unclemeat almost 9 years
    Thanks, I have found another expression which does not require calculating the modulus of negative numbers - at the expense of a few bytes (for CodeGolf).