Question

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?

Était-ce utile?

La 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.

Autres conseils

You can use a VBS script using Windows Scripting Host in a batch file, or Powershell I guess if that has better math capability.

I adapted this from a usenet post and the batch file below shows some examples.
You can use it to do some maths.

::vbs.bat
@echo off
>"%temp%\VBS.vbs" echo Set fso = CreateObject("Scripting.FileSystemObject") : Wscript.echo (%*)
cscript /nologo "%temp%\VBS.vbs"
del "%temp%\VBS.vbs"

The first command prints an ascii list of characters from 32 to 127.
The second prints the date 1 day ago
The other are as they say...

@echo off
for /l %%N in (32,1,127) do @call vbs right("00"+hex("%%N")+":",4)+chr(%%N)
for /f %%Y in ('vbs date-1') do set Yesterday=%%Y
echo %yesterday%
for /f %%P in ('vbs 4*atn(1^)') do echo PI = %%P
for /f %%S in ('vbs sqr(2^)') do echo Sq Root of2 = %%S
for /f %%a in ('vbs 6.1+8.2') do set num=%%a
echo %num%
Pause

Native batch is limited to signed 32-bit integers. There are libraries available to extend its capabilities - Google is your friend. Not sure what you mean by 'large' calculations - please exemplify.

Regardless, batch is S-L-O-W.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top