Basic BAT calculator command

I am trying to do a very basic 2 value input BAT file but I am struggling. I used a free template from Wikihow and re-adjusted but something is not right.

I want to calculate 100/(A/B+1) and I know for a fact that the Batch calculation ignores the "+1" for some reason and basically just calculates "100/(A/B). Please help. Thanks.

TITLE Calculator
ECHO OFF
CLS
:TOP
color 3f
Cls
:SUM
CLS
ECHO ---------------------------------------------------
ECHO[
ECHO                 Division
ECHO[
ECHO ---------------------------------------------------
ECHO[
set /p A=" Enter First Amount = "
ECHO[
set /p B=" Enter Second Amount = "
SET /A C=100/(A/B+1)
ECHO[
ECHO ---------------------------------------------------
ECHO Result %C%
PAUSE
GOTO:TOP

3 answers

  • answered 2018-02-13 02:09 Ctznkane525

    I suspect this is an order of operations issue.

    Remember that plus comes after division.

    You might need this instead:

    SET /A C=100/(A/(B+1))
    

    This will allow the B+1 to come before the division.

  • answered 2018-02-13 04:26 FatalBulletHit

    SET /A doesn't ignore the +1:

    E.g. SET /A 100/(10/2+1) outputs 16; the problem you most likely have is this:

    Any SET /A calculation that returns a fractional result will be rounded down to the nearest whole integer.

    (Source)


    However, it is possible to work around this issue:

    SETLOCAL EnableDelayedExpansion
    
    SET /A "var=100000/(10/2+1)"
    SET "fraction=%var:~-3%" & SET /A "var/=1000"
    IF !fraction:~-1! GEQ 5 SET /A "fraction+=10"
    SET "fraction=!fraction:~0,-1!"
    ECHO %var%.%fraction%
    

    Basically you multiply the number to be divided by 10^(n) and - after you set the fraction (%var:~-n%) - divide it by 10^(n) again. Then you check the last digit of the fraction for proper rounding and remove it (read more).

  • answered 2018-02-13 07:09 Gerhard Barnard

    I am assuming you were looking for:

     SET /A B=B+1
     SET /A C=100/(A/B)