Search code examples
batch-filecalculatortemporary-filesrunning-other-programs

Batch- do more advanced calculations


In batch, I have trouble doing more advanced calculations with set /a. Decimals won't work; for example set /a 5/2 only outputs 2 instead of 2.5. Also batch can't handle large calculations. Is there a way to just make a temp file (like vbs) or call on another program (like calculator) to do the calculation and return it back to the batch file?


Solution

  • The program below as an example of a Batch-JScript hybrid script that allows to evaluate any JScript expression:

    @if (@CodeSection == @Batch) @then
    
    @echo off
    
    rem Define an auxiliary variable to call JScript
    set JScall=Cscript //nologo //E:JScript "%~F0"
    
    for /F %%p in ('%JScall% Math.PI') do echo Intrinsic value of PI= %%p
    for /F %%P in ('%JScall% 4*Math.atan(1^)') do echo Calculated value of PI= %%P
    for /F %%S in ('%JScall% Math.sqrt(2^)') do echo Square Root of 2 = %%S
    for /F %%t in ('%JScall% 1/3') do set oneThird=%%t
    echo One third = %oneThird%
    for /F %%o in ('%JScall% %oneThird%*3') do echo One third times 3 = %%o
    
    goto :EOF
    
    @end
    
    // JScript section
    
    WScript.Echo(eval(WScript.Arguments.Unnamed.Item(0)));
    

    Output:

    Intrinsic value of PI = 3.14159265358979
    Calculated value of PI= 3.14159265358979
    Square Root of 2 = 1.4142135623731
    One third = 0.333333333333333
    One third times 3 = 0.999999999999999
    

    You may review the available JScript arithmetic functions at: http://msdn.microsoft.com/en-us/library/b272f386(v=vs.84).aspx

    This method allows to keep the JScript code in the same .BAT file and is simpler and faster than the VBScript code.