Home > front end >  Limit Output to only two decimal places
Limit Output to only two decimal places

Time:12-06

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

CodePudding user response:

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.

  • Related