Question

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?

Was it helpful?

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.

OTHER TIPS

This works for me. Could still be cleaned up a bit.

import fractions

def parse_multi_part_fraction(f):
    if '/' not in f:
        return float(f)
    parts = f.split(' ')
    total = 0.0
    for p in parts:
        if '/' in p:
            frac = fractions.Fraction(p)
            total += frac.numerator * (1.0 / frac.denominator)
        else:
            total += float(p)
    return total
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top