Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Limit Output to only two decimal places

Output:

number of water molecules in 1.0 gm of water is: 3.341842397336293e+22

Expected Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

number of water molecules in 1.0 gm of water is: 3.342e+22

Tried using round()

p = round(n,3)
n = 3.341842397336293e+22
p = round(n,3)
print(p)

output:

3.341842397336293e+22

and tried

  n = 3.341842397336293e+22
    print("%.3f"%n)

output :

33418423973362928713728.000

>Solution :

You can use .3e as the format:

n = 3.341842397336293e+22
print(f"... water is: {n:.3e}") # ... water is: 3.342e+22

'e': Scientific notation. For a given precision p, formats the number in scientific notation with the letter ‘e’ separating the coefficient from the exponent. The coefficient has one digit before and p digits after the decimal point, for a total of p + 1 significant digits.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading