Sum of two decimal values

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
sark
Posts: 7
Joined: 21 Feb 2020 07:37

Sum of two decimal values

#1 Post by sark » 05 Oct 2021 09:26

The below set variable outputs the sum of 6 and 2. This works fine, but only works with whole numbers. How, if possible, could I output values with decimal points. ie: 6.2+2.4 outputting 8.6.

Set /a S=6×2

%S%

Thanks

Mark

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

Re: Sum of two decimal values

#2 Post by Squashman » 05 Oct 2021 09:54

for /F "delims=" %%G IN ('powershell -command "2.4 + 6.2"') do set "result=%%G"

atfon
Posts: 178
Joined: 06 Oct 2017 07:33

Re: Sum of two decimal values

#3 Post by atfon » 05 Oct 2021 09:56

The command processor has a limitation when it comes to floating point arithmetic. Have a look at this workaround:

https://www.dostips.com/DtTipsArithmeti ... atingPoint

Note: You can get your decimal back with string manipulation on the result.

sark
Posts: 7
Joined: 21 Feb 2020 07:37

Re: Sum of two decimal values

#4 Post by sark » 05 Oct 2021 10:41

Thanks for the quick responses.

@atfon. l was reading the workaround you linked whilst you were replying. What exactly do you mean by string manipulation to recover the decimal point?

Thanks

Mark

atfon
Posts: 178
Joined: 06 Oct 2017 07:33

Re: Sum of two decimal values

#5 Post by atfon » 05 Oct 2021 11:28

sark wrote:
05 Oct 2021 10:41
What exactly do you mean by string manipulation to recover the decimal point?

Thanks

Mark
Hello Mark. You can extract the first digit and the last digit:

https://www.dostips.com/DtTipsStringMan ... LeftString

For the first digit, set "first=%str:~-1%" and for the last set "last=%str:~0,1%". Then you can set the entire term as set "whole=%first%.%last.%"

There are likely easier ways to do this that the Experts on this site could point out to you. For example, Squashman's powershell example or VBScript.

sark
Posts: 7
Joined: 21 Feb 2020 07:37

Re: Sum of two decimal values

#6 Post by sark » 05 Oct 2021 15:37

Thanks for that.

I'm incorperating into ffmpeg scripts so will take a closer look at the best approach for my needs.

Mark

Post Reply