[英]How to round float down to 3 decimal places?
I wrote a function to return the energy of a given wavelength.我写了一个 function 来返回给定波长的能量。 When I run the function the print statement returns the float
E
, but returns 20+ decimals and I cannot figure out how to round it down.当我运行 function 时,打印语句返回 float
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)
I tried doing this:我试过这样做:
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)
But that returned 0.000000J
.但这返回了
0.000000J
。 How can I fix my program to return 3 decimal places?如何修复我的程序以返回 3 个小数位?
The program returns an E value.程序返回一个 E 值。 ie
3.10118181818181815e-19J
.即
3.10118181818181815e-19J
。 I want it to return something like 3.1012e-19J
with fewer decimal places.我希望它返回类似
3.1012e-19J
的小数位数更少的内容。
Try this:尝试这个:
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)
or you can:或者您可以:
print("The energy of the " + color.lower() + " wave is " + str('{:.2e}'.format(E)) + "J.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.