How to make the ":. 0f" format not round my number

Asked

Viewed 140 times

5

I wanted to know how I use the format ":.0f" without rounding up the number.

I want to catch a input of seconds and turn it into minutes, here’s my code:

segundos = int(input())

minutos = segundos

while minutos > 60:
    temp = minutos / 60
    minutos = temp

print(f"Minutos: {minutos:.0f}")

I want it to print out the exact number of minutes without rounding up so I can take the rest and put in seconds.

But when I walk in with the input 650 for example, instead of giving me the value 10 (minutes), it gives me 11.

I know if I put .format(int(minutos)) he will return me the 10, but would have some way to specify with some argument in this ":.0f" that I don’t want it to end? How do I not do it?

  • print(f"Minutos: {minutos:.02f}") or without any formatting instruction with print(f"Minutos: {minutos}")

  • Just do not forget that the amount after the point is not in "seconds" - 1.5 minutes == 1m:30s

1 answer

4


Actually you are trying to solve the wrong problem. If you want the result of the division to be whole, use the operator entire-division // (two bars instead of one).

So you don’t have to worry about rounding up. And as you also said that "I want it to print out the exact number of minutes without rounding up so I can take the rest and put in seconds.", make the exact split also facilitates to get the amount of seconds remaining:

total_segundos = 650
minutos = total_segundos // 60
segundos = total_segundos - (minutos * 60)
# ou, nesse caso também poderia ser
# segundos = total_segundos % 60

print(f"{minutos} minutos e {segundos} segundos") # 10 minutos e 50 segundos

Since the results are now integers (and no longer floating point numbers), it is not necessary to specify the format (after all, .0f says to print the number with zero decimal places, and as the results are already integers, specify such format is unnecessary).


In this specific case, another option to get both values is to use divmod, which returns a tuple with the result of the entire division and the rest of this division:

total_segundos = 650
minutos, segundos = divmod(total_segundos, 60)
print(f"{minutos} minutos e {segundos} segundos") # 10 minutos e 50 segundos

Browser other questions tagged

You are not signed in. Login or sign up in order to post.