将分数转换为浮点数? [英] Convert fraction to float?
本文介绍了将分数转换为浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
种类类似于此问题的类似,但相反
Kind of like this question, but in reverse.
给出像1
,1/2
或1 2/3
这样的字符串,将其转换为浮点数的最佳方法是什么?我正在考虑根据情况使用正则表达式,但也许有人知道更好的方法或预先存在的解决方案.我希望可以只使用eval
,但是我认为第3种情况可以防止这种情况.
Given a string like 1
, 1/2
, or 1 2/3
, what's the best way to convert it into a float? I'm thinking about using regexes on a case-by-case basis, but perhaps someone knows of a better way, or a pre-existing solution. I was hoping I could just use eval
, but I think the 3rd case prevents that.
推荐答案
我稍微调整了 James的回答. /p>
I tweaked James' answer a bit.
def convert_to_float(frac_str):
try:
return float(frac_str)
except ValueError:
num, denom = frac_str.split('/')
try:
leading, num = num.split(' ')
whole = float(leading)
except ValueError:
whole = 0
frac = float(num) / float(denom)
return whole - frac if whole < 0 else whole + frac
print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5
这篇关于将分数转换为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文