Floating point division in a batch file

I know this is a very old topic, but I can’t found a simple Batch method in all previous answers, so I post here a pure Batch solution that is very simple to use.

Perform operations using fixed point arithmetic in Batch is simple. “Fixed point” means that you must set a number of decimals in advance and keep it throughout the operations. Add and subtract operations between two Fixed Point numbers are performed directly. Multiply and division operations requires an auxiliary variable, that we can call “one”, with the value of 1 with the right number of decimals (as “0” digits). After multiply, divide the product by “one”; before division, multiply the dividend by “one”. Here it is:

@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%!

For example:

Enter a number with 2 decimals: 3.76
3.76 + 2.54 = 6.30
3.76 - 2.54 = 1.22
3.76 * 2.54 = 9.55
3.76 / 2.54 = 1.48

Leave a Comment