# Digit_sum and problem with int(variable)

#1

Hello, my friends, I've got a problem with Part 15 of Python Course with a digit_sum function.

Please tell me, am I some kind of idiot or is this only a bug.

When I try to use function: int(4.0) the result is 4 -> that's correct.
But when I use int(variable), where variable is 4.0 too, function returns value 3 rather than 4.

As a confirmation I give you a screen:

Don't look at my commented function (I'm trying to make this exercise on crazy way)

#2

Funny thing about float numbers is that let's way you are dividing 23 by 10, you get 2.3 right?
2.3 may be an approximation as float numbers aren't always accurately represented.
So 2.3 can actually be 2.299999999999... and if you multiply it by 10 and then `int` that, it turns out to be 22.

Same with your case. That 4.0 can actually be 3.999999999999... hence why it becomes a 3.

There's a pretty fancy explanation to this which is known as binary floating point.

You can use the `round()` function and then `int()` to make the 3 into a 4.

Other languages also do this.

#3

Thank you so much I never met this situation when I programmed in other languages or PLC This is lesson for me to watch out for 'what' and 'how' I'm programming sth'. Again, thank you very much.

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.