如何将浮点数舍入到小数点后三位?
How to round float down to 3 decimal places?
我写了一个函数来 return 给定波长的能量。当我 运行 函数时,打印语句 return 是浮点数 E
,但是 return 是 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)
但是 returned 0.000000J
。
如何将我的程序固定到 return 3 位小数?
程序return是一个E值。即 3.10118181818181815e-19J
。
我希望它 return 类似于 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.")
你实际上快到了。
我找到了这个 Question
所以你要做的就是改变
str('{:.2f}'.format(E))
到
str('{:.3g}'.format(E))
我写了一个函数来 return 给定波长的能量。当我 运行 函数时,打印语句 return 是浮点数 E
,但是 return 是 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)
但是 returned 0.000000J
。
如何将我的程序固定到 return 3 位小数?
程序return是一个E值。即 3.10118181818181815e-19J
。
我希望它 return 类似于 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.")
你实际上快到了。 我找到了这个 Question
所以你要做的就是改变
str('{:.2f}'.format(E))
到
str('{:.3g}'.format(E))