Search code examples
batch-filecmdmodulo

CMD set /a, modulus, and negative numbers


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?


Solution

  • 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