1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Floating point division in a dos batch

Discussion in 'CMD' started by Joe Caverly, Sep 11, 2017.

  1. Joe Caverly

    Joined:
    Aug 28, 2009
    Messages:
    676
    Likes Received:
    8
    An example, which I came across at Stackoverflow, that demonstrates floating point division in a CMD file, which does not work in TCC.
    Code:
    @echo off
    setlocal EnableDelayedExpansion
    
    set decimals=2
    
    set /A one=1, decimalsP1=decimals+1
    for /L %%i in (1,1,%decimals%) do set "one=!one!0"
    
    :getNumber
    set /P "numA=Enter a number with %decimals% decimals: "
    if "!numA:~-%decimalsP1%,1!" equ "." goto numOK
    echo The number must have a point and %decimals% decimals
    goto getNumber
    
    :numOK
    set numB=2.54
    
    set "fpA=%numA:.=%"
    set "fpB=%numB:.=%"
    
    set /A add=fpA+fpB, sub=fpA-fpB, mul=fpA*fpB/one, div=fpA*one/fpB
    
    echo %numA% + %numB% = !add:~0,-%decimals%!.!add:~-%decimals%!
    echo %numA% - %numB% = !sub:~0,-%decimals%!.!sub:~-%decimals%!
    echo %numA% * %numB% = !mul:~0,-%decimals%!.!mul:~-%decimals%!
    echo %numA% / %numB% = !div:~0,-%decimals%!.!div:~-%decimals%!
    Joe
     
  2. rconn

    rconn Administrator
    Staff Member

    Joined:
    May 14, 2008
    Messages:
    9,854
    Likes Received:
    83
    Works with TCC 21.01.50. (Despite a couple of undocumented CMD "features", which were wholly unnecessary.)
     

Share This Page