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?
Asked
Active
Viewed 1,003 times
2 Answers
1
>>> 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
.

Katriel
- 120,462
- 19
- 136
- 170
-
Yeah, I wanted to know how to store it in the database. I was looking into overwriting the clean/to_python methods, but creating a custom field seems like the better option. – kgodey Nov 04 '10 at 22:05
-
Yes, I think it makes more sense to store them as fractions. Unfortunately I don't know Django, so can't help with the custom field; if you rephrase the question you might have more luck. – Katriel Nov 04 '10 at 22:27
-
That's fine, the Django documentation/code is pretty helpful and I got it working. Thank you! – kgodey Nov 05 '10 at 01:54
0
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

mgalgs
- 15,671
- 11
- 61
- 74