1

Say I have a variable called

time = 6.50

how can I split the number so that I can output to the user:

print("Your total time was %i minutes and %i seconds. " %(minute, second))

I thought about converting them to string but I need to be able to multiply the .50 part by 60 so I can get the total seconds.

jo13
  • 209
  • 2
  • 3
  • 11

2 Answers2

3

You can also use divmod , as -

minutes, seconds = divmod(int(time * 60), 60)

If you want the seconds to also have millisecond (floating point precision) , you can remove the conversion to int and do - divmod(time * 60, 60) .

Demo -

>>> time = 6.50
>>> divmod(time * 60, 60)
(6.0, 30.0)
>>> time = 6.55
>>> divmod(time * 60, 60)
(6.0, 33.0)
>>> time = 6.53
>>> divmod(time * 60, 60)
(6.0, 31.80000000000001)
>>> time = 6.55
>>> divmod(int(time * 60), 60)
(6, 33)

But please note, floating point arithematic is not precise, so you may get approximate values instead of exact accurate results.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
2
time = 6.50
minute, second = int(time), (time%1)*60
print("Your total time was %i minutes and %i seconds. " %(minute, second))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308