I have been looking at the mathematical functions but unfortunately I cannot find the mathematical formula for sum of digits e.g. 6939 = 6+9+3+9 = 27
For example, if I want to code the sum of digits for an index price re FTSE 100 at close, 6939, what will be the formula in code? Kindly help please.
There’s no built-in function to manipulate single digits.
You can achieve that by a doing some divisions and multiplications by ten, then rounding the number to subtract the result from the original number to get the desired digit:
N = 6939 //it can be CLOSE, ... etc or ROUND(CLOSE),... etc to make it an integer
T = 0
//right to left
WHILE N > 0 //exit the iteration when N = 0
x = round((N / 10) - 0.5) * 10 //get 693.9, then 693.0, then 6930
T = T + (N - x) //T = itself + 9 (actually 6939 - 6930)
N = x / 10 //save the new N (6930)
WEND //repeat for the next digit
Roberto, thanks for your prompt reply and this is really helpful.
The correct comment in line 7 is:
//save the new N (693)