Reputation: 69
I wrote a function to return the energy of a given wavelength. 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.
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
.
How can I fix my program to return 3 decimal places?
The program returns an E value. i.e. 3.10118181818181815e-19J
.
I want it to return something like 3.1012e-19J
with fewer decimal places.
Upvotes: 0
Views: 275
Reputation: 36
You are actually nearly there. I found this Question
So all you have to do is change
str('{:.2f}'.format(E))
to
str('{:.3g}'.format(E))
Upvotes: 2
Reputation: 2804
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.")
Upvotes: 0