0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Jamba
  • 59
  • 1
  • 5
  • Give a look here: https://stackoverflow.com/questions/9232256/round-up-to-second-decimal-place-in-python – JLeno46 Jan 04 '21 at 15:38

2 Answers2

2

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))

Sico-CD
  • 36
  • 3
  • No need for the `str` wrapper: the format call result is already string, so `'{:.3g}'.format(E)` is enough. (You could also spell this more concisely as `format(E, '.3g')`, but in the OP's context there's surrounding text, so it make sense to use the string interpolation facility of `format` in place of all the string additions.) – Mark Dickinson Jan 04 '21 at 16:32
0

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.")
dimay
  • 2,768
  • 1
  • 13
  • 22