JSI Tip 4533. How do I perform accurate and/or complex math in a batch?

Jerold Schulman

December 10, 2001

1 Min Read
ITPro Today logo in a gray background | ITPro Today


When you use the arithmetic operations of the SET command, the results are truncated to aninteger. A SET /? commands includes:

The /A switch specifies that the string to the right of the equal signis a numerical expression that is evaluated.  The expression evaluatoris pretty simple and supports the following operations, in decreasingorder of precedence:    ()                  - grouping    * / %               - arithmetic operators    + -                 - arithmetic operators    << >>               - logical shift    &                   - bitwise and    ^                   - bitwise exclusive or    |                   - bitwise or    = *= /= %= += -=    - assignment      &= ^= |= <<= >>=    ,                   - expression separator

Thus:

set /a numerator=7set /a divisor=4set /a dividend=%numerator% / %divisor%@echo dividend=%dividend%

returns a 1. You can use the modulus operator to return the remainder, but if you need accurate decimal results, and / or complex math functions, use the Windows Scripting Host.

You must have your default host set so CScript.exe, so if yours is set to WScript.exe, use cscript.exe //H:cscript in the beginning of the batch and cscript.exe //H:wscript before exiting.

Prior to using Visual Basic arithmetic expressions in your batch, you must create domath.vbs in your path:

Set objArgs = WScript.Arguments
wscript.echo eval(objArgs(0))

Your new batch can look like:

cscript.exe //H:cscriptset /a numerator=7set /a divisor=4for /f %%i in ('domath //nologo %numerator%/%divisor%') do set dividend=%%i @echo dividend=%dividend%cscript.exe //H:wscript

In addition to mathematical expressions, you can use Math Methods:

@echo offcscript.exe //H:cscriptfor /f %%i in ('domath //nologo "%numerator% mod %divisor%"') do set mod=%%i @echo mod=%mod%cscript.exe //H:wscript

or

@echo offcscript.exe //H:cscriptset /a numerator=7set /a divisor=4for /f %%i in ('domath //nologo "Round(%numerator%/%divisor%)"') do set dividend=%%i @echo dividend=%dividend%cscript.exe //H:wscript

You can use complex expressions like:

@echo oncscript.exe //H:cscriptset /a numerator=7set /a divisor=4for /f %%i in ('domath //nologo "(%numerator%^2+1)*2/%divisor%"') do set answer=%%i @echo answer=%answer%cscript.exe //H:wscript

NOTE: Make sure that you use valid arguments.


Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like