简体   繁体   中英

Limit Output to only two decimal places

Output:

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

Expected Output:

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

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.

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