The problem
def number_adder():
# [...]
sum += math.floor(number)
number -= math.floor(number)
print(number)
# Prints: 0.22219999999999995
# [...]
I added a print
statement to check the value of number
out and given the input 22222
the output for number
at that point was: 0.22219999999999995
. That happens because Python
doesn't execute floating point operations with infinite precision, so that's the most precise value it can get for the substraction given sum
and number
.
(Check Python error in basic subtraction? and Python error in basic subtraction? as examples).
Naturally, when looping through the decimals
of number
the following happens:
for digit in range(number_of_digit - 1):
number = number * 10
sum += math.floor(number)
number -= math.floor(number)
0.2221999...5 <-- Adds a 2
0.221999...5 <-- Adds a 2
0.21999...5 <-- Adds a 2
0.19999...5 <-- Adds a 1
And that's the reason why you get 9 as the final number (Adding up to the previous value of 2).
Possible solution:
Replace number -= math.floor(number)
in the two lines that I point out with number = round(number - math.floor(number), number_of_digit - 1)
to get back the original decimal values by rounding
import math
def number_adder():
# [...]
sum += math.floor(number)
# Round number to `number_of_digit - 1` decimals
# This will yield: `0.2222` for the original input `22222`
number = round(number - math.floor(number), number_of_digit - 1) # (1) <---
for digit in range(number_of_digit - 1):
number = number * 10
sum += math.floor(number)
# Round `number` again here as this is a new floating point operation
# (number_of_digit - digit - 2) are the remaining decimal points
number = round(number - math.floor(number), number_of_digit - digit - 2) # (2) <---
print("The sum of all digits of the value is, ", sum)