Starting with an example that fails the "multiply by 10" approach:
Note: the following fails when the denominator is either 1, 2 or 5.
>>> math.modf(22.7)[0]*10 6.999999999999993You can use the fractions module:
Note: the following fails when the denominator is either 1, 2 or 5.
>>> from fractions import Fraction >>> Fraction(22.7) Fraction(6389481971331891, 281474976710656) >>> Fraction(22.7).limit_denominator(10) Fraction(227, 10) >>> a=Fraction(22.7).limit_denominator(10) >>> divmod(a.numerator, a.denominator) (22, 7)The following version should handle the cases when the denominator is not 10. It also uses the output of modf directly.
>>> a=Fraction(math.modf(22.7)[0]).limit_denominator(10) >>> divmod(10,a.denominator)[0]*a.numerator 7