Skip navigation

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


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

The /A switch specifies that the string to the right of the equal sign
is a numerical expression that is evaluated.  The expression evaluator
is pretty simple and supports the following operations, in decreasing
order of precedence:

    ()                  - grouping
    * / %               - arithmetic operators
    + -                 - arithmetic operators
    << >>               - logical shift
    &                   - bitwise and
    ^                   - bitwise exclusive or
    |                   - bitwise or
    = *= /= %= += -=    - assignment
      &= ^= |= <<= >>=
    ,                   - expression separator
Thus:
set /a numerator=7
set /a divisor=4
set /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:cscript
set /a numerator=7
set /a divisor=4
for /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 off
cscript.exe //H:cscript
for /f %%i in ('domath //nologo "%numerator% mod %divisor%"') do set mod=%%i 
@echo mod=%mod%
cscript.exe //H:wscript
or
@echo off
cscript.exe //H:cscript
set /a numerator=7
set /a divisor=4
for /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 on
cscript.exe //H:cscript
set /a numerator=7
set /a divisor=4
for /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.


Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish