Python 如何将浮点值舍入到小数点后3位?
我写了一个函数来返回给定波长的能量。当我运行函数时,print语句返回floatPython 如何将浮点值舍入到小数点后3位?,python,floating-point,Python,Floating Point,我写了一个函数来返回给定波长的能量。当我运行函数时,print语句返回floatE,但返回20+位小数,我不知道如何将其取整 def FindWaveEnergy(color, lam): c = 3.0E8 V = c/lam h = 6.626E-34 E = h*V print("The energy of the " + color.lower() + " wave is " + str(E) + "J.")
E
,但返回20+位小数,我不知道如何将其取整
def FindWaveEnergy(color, lam):
c = 3.0E8
V = c/lam
h = 6.626E-34
E = h*V
print("The energy of the " + color.lower() + " wave is " + str(E) + "J.")
FindWaveEnergy("red", 6.60E-7)
我试着这样做:
def FindWaveEnergy(color, lam):
c = 3.0E8
V = c/lam
h = 6.626E-34
E = h*V
print("The energy of the " + color.lower() + " wave is " + str('{:.2f}'.format(E)) + "J.")
FindWaveEnergy("red", 6.60E-7)
但是它返回了0.000000J
。
如何修复程序以返回小数点后3位
程序返回一个E值。i、 e.3.1011815E-19J
。
我希望它返回类似于3.1012e-19J
的内容,小数位数更少。尝试以下操作:
def FindWaveEnergy(color, lam):
c = 3.0E8
V = c/lam
h = 6.626E-34
E = str(h*V).split("e")
print("The energy of the " + color.lower() + " wave is " + E[0][:4] + "e" + E[-1] + "J.")
FindWaveEnergy("red", 6.60E-7)
或者你可以:
print("The energy of the " + color.lower() + " wave is " + str('{:.2e}'.format(E)) + "J.")
试试这个:
def FindWaveEnergy(color, lam):
c = 3.0E8
V = c/lam
h = 6.626E-34
E = str(h*V).split("e")
print("The energy of the " + color.lower() + " wave is " + E[0][:4] + "e" + E[-1] + "J.")
FindWaveEnergy("red", 6.60E-7)
或者你可以:
print("The energy of the " + color.lower() + " wave is " + str('{:.2e}'.format(E)) + "J.")
你实际上就快到了。 我找到了这个 所以你所要做的就是改变
str(“{.2f}.”格式(E))
到
str({:.3g}.format(E))
你实际上就快到了。
我找到了这个
所以你所要做的就是改变
str(“{.2f}.”格式(E))
到
str('{.3g}.format(E))
查看这里:查看这里:不需要str
包装器:格式调用结果已经是字符串,所以'{.3g}.format(E)
就足够了。(您也可以将其更简洁地拼写为format(E,'.3g')
,但在OP的上下文中有周围的文本,因此使用format
的字符串插值功能代替所有字符串添加是有意义的。)不需要str
包装器:格式调用结果已经是字符串,所以'{.3g格式(E)
就足够了。(您也可以将其更简洁地拼写为格式(E,'.3g')
,但在OP的上下文中有周围的文本,因此使用格式的字符串插值功能代替所有字符串添加是有意义的。)