Search code examples
pythondjangodjango-formsfractionsstring-parsing

Parsing a fraction in a Django form


I'm using Django on the backend and jQuery on the front end. I would like to accept both fractions and whole numbers (like "1/2", "1 1/4" or "2", for ingredient quantities in a recipe.) I'm using a FloatField to store these values. What is the best way to convert these fractions/whole numbers to floats?


Solution

  • >>> import fractions
    >>> fractions.Fraction("1")
    Fraction(1, 1)
    >>> fractions.Fraction("1/2")
    Fraction(1, 2)
    

    Unfortunately, the fraction constructor doesn't handle mixed fractions ("1 1/2") so you will have to write something to parse those yourself. You can store them in the database either with a custom field or by casting them to float.