简体   繁体   中英

How to round float down to 3 decimal places?

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. ie 3.10118181818181815e-19J . I want it to return something like 3.1012e-19J with fewer decimal places.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM