Howto calc math expressions with brackets in "if"?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
pstein
Posts: 125
Joined: 09 Nov 2011 01:42

Howto calc math expressions with brackets in "if"?

#1 Post by pstein » 20 Jan 2015 06:24

I would like to perform numeric calculations in DOS. I code simplified the following:

set /p func=Enter function=
set /p a=Enter a=
set /p b=Enter b=
set /p c=Enter c=
If [func]==[x] (
set /a res=^(%a% - %b%^) / %c%
Echo res=%res%)
Echo End of calcs

The problem is that the script doees NOT echo the result.

Whats wrong?

I guess the brackets are the culprit. I masked them with carets but it didn't help.

So how else can I perform a function calc WITH brackets INSIDE an "if"/"else" branch enclosed itself by brackets?

Further question: How can I check if a variable value is numeric?

Further question: How can I check if a variable value is numeric and greater zero?

Peter

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: Howto calc math expressions with brackets in "if"?

#2 Post by Squashman » 20 Jan 2015 07:25

Your IF is testing if func is equal go X. It should be testing the value of %func% is equal to X.

pstein
Posts: 125
Joined: 09 Nov 2011 01:42

Re: Howto calc math expressions with brackets in "if"?

#3 Post by pstein » 20 Jan 2015 07:37

Squashman wrote:Your IF is testing if func is equal go X. It should be testing the value of %func% is equal to X.


Yes, you are rigth. Its a typo. Sorry.
But the core problems remains even if I code

...
If [%func%]==[x] (
...

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Howto calc math expressions with brackets in "if"?

#4 Post by foxidrive » 20 Jan 2015 08:01

EDIT: I wasn't clear - this is two answers to the questions asked.

Double quotes protect the brackets.

Code: Select all

for /f "delims=0123456789" %%a in ("%variable%") do echo not numeric.

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: Howto calc math expressions with brackets in "if"?

#5 Post by Squashman » 21 Jan 2015 14:51

Your RES variable is not echoing to the screen because it is inside a code block and you are not using delayed expansion. Move that echo outside of the parentheses or use delayed expansion.

Code: Select all

@echo off
setlocal enabledelayedexpansion

set /p func=Enter function=
set /p a=Enter a=
set /p b=Enter b=
set /p c=Enter c=
If [%func%]==[x] (
   set /a "res=(%a% - %b%) / %c%"
   Echo res=!res!
)
Echo End of calcs
pause

Post Reply