Floating Point Numbers in batch

Microsoft Windows
Post Reply
User avatar
Simon Sheppard
Posts: 189
Joined: 2021-Jul-10, 7:46 pm
Contact:

Floating Point Numbers in batch

Post by Simon Sheppard »

First off let me prefix this by saying the easy and robust way to work with Floating point Numbers, is just passing them to PowerShell:

Code: Select all

powershell.exe 12.9999999 + 2105001.01
But if you really want to do this in batch:

Code: Select all

@Echo off
:: Floating point Numbers to add
:: These must contain a decimal point and be less than 2.1 million
set sum1=12.9999999
set sum2=2105001.01
Echo inputs [%sum1%] + [%sum2%]
:: Get the integer portion
set/a sum1int=sum1
set/a sum2int=sum2
:: echo %sum1int%
:: echo %sum2int%

:: Get the decimal fraction portion
set "sum1frac=%sum1:*.=%000
set "sum2frac=%sum2:*.=%000

::truncate decimal fraction to exactly 3 characters
set "sum1frac=%sum1frac:~0,3%"
set "sum2frac=%sum2frac:~0,3%"
:: echo %sum1frac%
:: echo %sum2frac%

:: Add the numbers as a large integer
set/a "_addition=%sum1int%%sum1frac%+%sum2int%%sum2frac%"
:: echo sum %_addition%

:: split the integer and 3-digit fractional part and insert a decimal point.
Set _Int=%_addition:~0,-3%
Set _Fra=%_addition:~-3%
Echo result %_Int%.%_Fra%
The limited numeric range compared to a 32 bit int is because we are using 3 digits for the fractional part, to make this true floating point, you will have to adjust that to fit the numbers you are working with, I leave that as an exercise for the reader.
Post Reply