[Tutor] Limitation of int() in converting strings

eryksun eryksun at gmail.com
Thu Jan 3 13:04:03 CET 2013


On Tue, Jan 1, 2013 at 12:07 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> Again, I was mistaken. x%1 is not suitable to get the fraction part of a
> number in Python: it returns the wrong result for negative values. You need
> math.modf:
>
> py> x = -99.25
> py> x % 1  # want -0.25
> 0.75
> py> math.modf(x)
> (-0.25, -99.0)

math.modf wraps libm's modf, which takes a double. This isn't suitable
for Decimal, Fraction, or a custom number type. What's wrong with
using math.trunc for this?


More information about the Tutor mailing list