Csarg
Csarg

Reputation: 363

Python: Rounding output of the time module

This is the code I have for measuring how long it took the user to complete the program:

start_time = time.time() # Sits at the top of my code
print("%f seconds" % (time.time() - start_time)) # Goes at the bottom of my code

My question is, how do I round the output of this to one decimal place? For example, if my output was 3.859639 seconds how would I present this like: 3.8 Secounds?

Upvotes: 0

Views: 528

Answers (3)

Jon Clements
Jon Clements

Reputation: 142146

Primitive way... multiply out, truncate the rest, then divide again:

diff = time.time() - start_time
rounded_down = int(diff * 10) / 10 # = 3.8

Upvotes: 0

Anurag Verma
Anurag Verma

Reputation: 495

Use round function with second argument as 1

start_time = time.time() # Sits at the top of my code
x=round((time.time() - start_time),1)
print x

Upvotes: 0

ilyakhov
ilyakhov

Reputation: 1319

It looks like you've forgotten ".1" before "f". Try this:

print("%.1f seconds" % (time.time() - start_time))

Upvotes: 5

Related Questions