Question

Remainders with fractional divisions not working in Python. For example,

>>> 59.28%3.12
3.119999999999999
>>> 59.28/3.12
19.0

Is there any way to get 0.0 as the output of 59.28%3.12

Was it helpful?

Solution

I don't know why, I don't know details of modulo implementation for floats, however this works fine:

from decimal import Decimal
Decimal("59.28") % Decimal("3.12")

EDIT: Note that you have to use quotes " (i.e. strings) in constructors. Otherwise it will try to interpret both numbers as floats which is the source of the problem (incorrect approximation).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top