Upendra Dama
Upendra Dama

Reputation: 99

How to keep trailing zeroes after rounding in Python

How can I get the output with trailing zeroes after rounding in a Single line of code.

My code:- 
   print (df[['smoker','age']].corr().round(4).iloc[0]['age'])

Current output :- -0.025

Expected output: -0.0250

Upvotes: 1

Views: 164

Answers (2)

mattyx17
mattyx17

Reputation: 816

print("{0:.4f}".format(df[['smoker','age']].corr().round(4).iloc[0]['age']))

The 0 in {0:.4f} refers to the first item in the format call. For example

"{0} - {1}".format(x, y)

would produce the string "x y" but with the values of x an y.

The .4f refers to using 4 digits floating point precision

Upvotes: 1

Sebastian Baltser
Sebastian Baltser

Reputation: 758

You could use the format option provided with the f-string functionality:

print(f"{df[['smoker','age']].corr().round(4).iloc[0]['age']:.4f}")

Upvotes: 2

Related Questions