Menu

Setting variables in a DOS batch file.

Ryan Shillington

You can use calc to do complex math in a DOS Batch file. I should warn you that if you're doing any kind of heavy calculations in Batch, you probably have the wrong language. Consider using Javascript (ie. Node JS), Ruby, Python or AutoIt instead. Even Powershell is probably a better choice.

Regardless, here's the syntax on how to do it:

for /f %%A in ('calc <your expression here>') do set "MyVariable=%%A"

So here's an example batch file:

@echo off
for /f %%A in ('calc 16 * 5') do set "MyVariable=%%A"
echo Multiplication Answer = %MyVariable%
REM Note the extra escaping of the carrot (^) when doing 10^3
for /f %%A in ('calc 10^^^^3') do set "MyVariable=%%A"
echo Power answer = %MyVariable%
REM Note the escaping of the bracket
for /f %%A in ('calc sin(30^)') do set "MyVariable=%%A"
echo Sin answer = %MyVariable%

set someThing=34
for /f %%A in ('calc %MyVariable% / %someThing%') do set "MyVariable=%%A"
echo Using other variables to divide = %MyVariable%

And here's the output when you run it: