如果以十进制形式收到的值是一个空字符串,我该如何将其转换为浮点数?
Posted
技术标签:
【中文标题】如果以十进制形式收到的值是一个空字符串,我该如何将其转换为浮点数?【英文标题】:If the value recieved in a Decimal Form is an empty string how can I convert it to a float number? 【发布时间】:2022-01-11 09:40:28 【问题描述】:在我的页面上,我以表格形式向用户询问各种事情,因为它是一个可以做各种事情的计算器,现在你看,问题是如果用户没有 bf 的值,我想提供选项使用不同的值进行计算,这就是为什么我需要的是 False,所以首先我要归档的是,如果表单为空我想作为 0 或 False 传递,我该如何归档?
我有以下表格:
class CMForm(forms.Form):
age = forms.DecimalField(max_digits=2, decimal_places=0, min_value=15, max_value=80)
sex = forms.ChoiceField(choices=sex)
pregnant = forms.BooleanField(initial=False, required=False)
lactating = forms.BooleanField(initial=False, required=False)
weight = forms.DecimalField(max_digits=4, decimal_places=1, max_value=635)
height = forms.DecimalField(max_digits=4, decimal_places=1, max_value=272)
bf = forms.DecimalField(label='Body Fat(not required)', help_text='%', required=False, decimal_places=1, min_value=1, max_value=80)
activeness = forms.ChoiceField(choices=activity_level)
units = forms.ChoiceField(choices=units)
这个观点:
def cmr(request):
a = float(request.GET['age'])
bf = float(request.GET.get('bf', 0))
s = str(request.GET['sex'])
g = 0
if s == 'female':
g = 1
w = float(request.GET['weight'])
h = float(request.GET['height'])
act = str(request.GET['activeness'])
u = str(request.GET['units'])
p = str(request.GET.get('pregnant', 0))
lac = str(request.GET.get('lactating', 0))
dci = 0
bmrm = 10*w+6.25*h-5*a+5
bmrf = 10*w+6.25*h-5*a-161
bmi = round(w/(h/100)**2, 1)
if bf is False:
bf = round(-44.988 + (0.503 * a) + (10.689 * g) + (3.172 * bmi) - (0.026 * bmi**2) + (0.181 * bmi * g) - (0.02 * bmi * a) - (0.005 * bmi**2 * g) + (0.00021 * bmi**2 * a), 1)
tbf = w*(bf/100)
ffm = w*(1-(bf/100))
ffmi = ffm/(h/100)**2
nffmi = ffmi+6.1*(1.8-(h/100))
if p == 'on':
dci = 300
if lac == 'on':
dci = dci+500
if s == 'male':
bmr = dci+bmrm
dcis = bmrm*1.2
dcil = bmrm*1.375
dcim = bmrm*1.55
dciv = bmrm*1.725
dcie = bmrm*1.9
else:
bmr = dci+bmrf
dcis = dci+bmrf*1.2
dcil = dci+bmrf*1.375
dcim = dci+bmrf*1.55
dciv = dci+bmrf*1.725
dcie = dci+bmrf*1.9
context = 'dci': round(int(dci)),
'p': p,
'lac': lac,
'bmr': int(bmr),
'dcis': int(dcis),
'dcil': int(dcil),
'dcim': int(dcim),
'dciv': int(dciv),
'dcie': int(dcie),
'act': act,
'bmi': bmi,
'bf': bf,
'tbf': round(tbf, 1),
'ffm': round(ffm, 1),
'ffmi': round(ffmi, 1),
'nffmi': round(nffmi, 1),
return render(request, "calorie_maintenance_result.html", context)
我收到以下错误:
could not convert string to float: ''
【问题讨论】:
【参考方案1】:您可以使用or
;给定一个字符串s
,如果s
为空,s or 0
将评估为0
:
s = ''
print(float(s or 0)) # 0.0
s = '123'
print(float(s or 0)) # 123.0
这是因为(在 python 中)x or y
如果x
为真,则返回x
,如果x
为假,则返回y
。由于空字符串是“假的”,'' or 0
等于 0
。
【讨论】:
以上是关于如果以十进制形式收到的值是一个空字符串,我该如何将其转换为浮点数?的主要内容,如果未能解决你的问题,请参考以下文章