Consider the following self commented code. I tried to keep in simple
>>> from fractions import Fraction
>>> def Arch2Float(num):
#First Partition from Right so that the Feet and Unit always
#Remains aligned even if one of them is absent
ft,x,inch=num.rpartition("\'")
#Convert the inch to a real and frac part after stripping the
#inch (") identifier. Note it is assumed that the real and frac
#parts are delimited by '-'
real,x,frac=inch.strip("\"").rpartition("-")
#Now Convert every thing in terms of feet which can then be converted
#to float. Note to trap Error's like missing or invalid items, its better
#to convert each items seperately
result=0
try:
result = int(ft.strip("\'"))
except ValueError:
None
#Convert the real inch part as a fraction of feet
try:
result += Fraction(int(real),12)
except ValueError:
None
#Now finally convert the Fractional part using the fractions module and convert to feet
try:
result+=Fraction(frac)/12
except ValueError:
None
return float(result)
Acid Test
>>> print Arch2Float('15-3/4"') # 15-3/4" (without ft)
1.3125
>>> print Arch2Float('12\' 6-3/4"') #12' 6-3/4"
12.5625
>>> print Arch2Float('12\'6-3/4"') #12'6-3/4" (without space)
12.5625
>>> print Arch2Float('3/4"') #3/4" (just the inch)
0.0625
>>> print Arch2Float('15\'') #15' (just ft)
15.0
>>> print Arch2Float('15') #15 (without any ascent considered as inch)
1.25
Converting from Float to Architecture would be easy as you don't have to take the pain to parsing
>>> def Float2Arch(num):
num=Fraction(num)
ft,inch=Fraction(num.numerator/num.denominator),Fraction(num.numerator%num.denominator)/num.denominator*12
real,frac=inch.numerator/inch.denominator,Fraction(inch.numerator%inch.denominator,inch.denominator)
return '{0}\' {1}-{2}"'.format(ft,real,frac)
Acid Test
>>> print Float2Arch(Arch2Float('12\' 6-3/4"'))
12' 6-3/4"
>>> print Float2Arch(Arch2Float('15-3/4"'))
1' 3-3/4"
>>> print Float2Arch(Arch2Float('12\'6-3/4"'))
12' 6-3/4"
>>> print Float2Arch(Arch2Float('3/4"'))
0' 0-3/4"
>>> print Float2Arch(Arch2Float('15\''))
15' 0-0"
>>> print Float2Arch(Arch2Float('15'))
1' 3-0"
>>>
Note*** Its important to keep the float representation in either the lowest denominator (inch) or the highest represented denominator (feet). I opted for the highest in this case feet. If you wan't to lower it you can multiply it by 12.
Update to cater Rounding Request
(Not sure if this is elegant but does the Job)
def Float2Arch(num):
num=Fraction(num)
ft,inch=Fraction(num.numerator/num.denominator),Fraction(num.numerator%num.denominator)/num.denominator*12
real,frac=inch.numerator/inch.denominator,Fraction(inch.numerator%inch.denominator,inch.denominator)
for i in xrange(1,17):
if Fraction(frac) < Fraction(1.0/16*i): break
frac=Fraction(1.0/16*i)
if frac>= 1:
real+=1
frac=0
return '{0}\' {1}-{2}"'.format(ft,real,frac)