you cannot do this with batch.It only works with integers. But you can use Jscript or powershell:
>powershell 5.6+3.1 8.7
For jscript you need to create an extra bit and call it (e.g. jscalc.bat):
@if (@x)==(@y) @end /***** jscript comment ****** @echo off cscript //E:JScript //nologo "%~f0" %* exit /b 0 @if (@x)==(@y) @end ****** end comment *********/ WScript.Echo(eval(WScript.Arguments.Item(0)));
Example:
>jscalc.bat "4.1+4.3" 8.4
remember that jscript above is not very stable and will not handle a bad formatted expression.
To set the result to a variable in both cases, you will need a FOR /F
wrapper:
>for /f "delims=" %# in ('powershell 5.6+3.1') do set result=%# >set result=8.7 >for /f "delims=" %# in ('jscalc 5.6+3.1') do set result=%# >set result=8.7
Most likely you installed powershell, but it is not available on all computers (not installed by default in Vista, XP, 2003), so if you donβt have it, you will need jscalc.bat
And also you can use jscript.net (OTHER jscript). Creating a .bat file that uses this is a bit more verbose and creates a small .exe file, but is also an option. Here is jsnetcalc.bat
:
@if (@X)==(@Y) @end /****** silent jscript comment ****** @echo off :::::::::::::::::::::::::::::::::::: ::: compile the script :::: :::::::::::::::::::::::::::::::::::: setlocal if exist "%~n0.exe" goto :skip_compilation :: searching the latest installed .net framework for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do ( if exist "%%v\jsc.exe" ( rem :: the javascript.net compiler set "jsc=%%~dpsnfxv\jsc.exe" goto :break_loop ) ) echo jsc.exe not found && exit /b 0 :break_loop call %jsc% /nologo /out:"%~n0.exe" "%~f0" :::::::::::::::::::::::::::::::::::: ::: end of compilation :::: :::::::::::::::::::::::::::::::::::: :skip_compilation :: :::::::::: "%~n0.exe" %* :::::::: :: endlocal exit /b 0 ****** end of jscript comment ******/ import System; var arguments:String[] = Environment.GetCommandLineArgs(); Console.WriteLine( eval(arguments[1]) );
Example:
>jsnetcalc.bat 4.5+7.8 12.3
And another way that MSHTA uses (the expression that you want to evaluate is set in the expression):
@echo off setlocal :: Define simple macros to support JavaScript within batch set "beginJS=mshta "javascript:close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(eval(" set "endJS=)));"" set "expression=8.5+3.5" :: FOR /F does not need pipe for /f %%N in ( '%beginJS% %expression% %endJS%' ) do set result=%%N echo result=%result%
You can edit to accept arguments like the examples above ...