How to sum digits of a number

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
gkick17
Posts: 5
Joined: 07 Jan 2021 15:21

How to sum digits of a number

#1 Post by gkick17 » 07 Jan 2021 15:28

Hi all,

did this a long time ago but have forgotten.
If I have a number eg 7292 and I want to basically add all the digits to generate the result of 20, how can I accomplish this ?
Thanks for your thoughts

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

Re: How to sum digits of a number

#2 Post by Squashman » 07 Jan 2021 22:18

Code: Select all

@echo off
setlocal
SET "number=7292"
set "sum=0"
for /F "delims=" %%G IN ('cmd /u /c "echo %number%"^|find /V ""') do (
    set /A sum+=%%G
)
echo SUM IS: %sum%
endlocal
pause
Output

Code: Select all

C:\Users\Squashman\Desktop>sum.bat
SUM IS: 20
Press any key to continue . . .

gkick17
Posts: 5
Joined: 07 Jan 2021 15:21

Re: How to sum digits of a number

#3 Post by gkick17 » 07 Jan 2021 22:27

Thank you, very much appreciated ! Working like a treat

Post Reply