What is the "%%" arithmetic in a batch file?

Sorry if this is a bit of a dummy question, but I have no idea what the %% arithmetic is. When I set a to 30 %% 35, it sets a to the value 30. But if I switch the numbers around, it sets a to the value 5. I just don't understand this.

@echo off
set /a a=30 %% 35
echo %a%
pause

2 Answers

%% is the modulus operator - that is, it performs integer division of its left argument by its right argument, and returns the remainder. SS64 on SET explains all of the allowed operators in the arithmetic SET command.

As @IvanMilyakov indicated in the comments, if you are doing a SET /A ... from the command line directly, rather than in a batch file, you would use % instead of %%; within a batch file, you need to double it to prevent it from being treated as a variable escape.

2

A % B at the prompt is A %% B in a batch, because the % symbol is special and needs to be 'escaped' in a batch. In the case of the % character, the escape character is another % character.

As Jeff Zeitlin says, the % or %% operator is the modulus operator, and gives the remainder after dividing A by B so 35 % 30 gives 5 because when you divide 35 by 30 you get the answer 1 and 5 left over, also you would get 5 from 65 % 30, 95 % 30 and so on. If B is larger than A the result of A % B will always be A. This is why 30 % 35 returns 30.

You can try set /a operations at the prompt. Try set /a 8%7 and see what you get. You don't need spaces.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like