Nik So
Nik So

Reputation: 16821

ruby convert hundredth seconds to timestamp optimization

Hey! I want to convert "123456" to "00:20:34.56" where the two digits to the right of the decimal point is in hundredth of a second. So 00:00:00.99 + 00:00:00.01 = 00:00:01.00

What I have: def to_hmsc(cent) h = (cent/360000).floor cent -= h*360000 m = (cent/6000).floor cent -= m*6000 s = (cent/100).floor cent -= s*100

"#{h}:#{m}:#{s}.#{s}" end

does this: to_hmsc("123456") #=> "0:20:34.56"

Question 1: I mean,this is ruby, I find the part ' cent -=... ' rather clunky. Can you see any way to shorten the entire process?

Question 2: This has been asked a million times before, but please share whatever you've got: what's the shortest way to add leading zero to the digits. so that to_hmsc("123456") #=> "00:20:34.56"

Thanks!

Upvotes: 1

Views: 558

Answers (1)

Mladen Jablanović
Mladen Jablanović

Reputation: 44090

Time.at(123456/100.0).strftime('%H:%M:%S.%2N')
#=> "01:20:34.56"

BTW, you should be careful with data types in Ruby, as it is strong-typed language. You can't pass a string to a method and expect it to work with it as it is a number.

Zero padding can be done in multiple ways. Usually, it is performed when formatting strings:

"%04d" % 12
#=> "0012"

Take a look at sprintf documentation for full reference.

PS. It seems that %2N doesn't work in Ruby <= 1.8.7. So here's the ugly version:

t=Time.at(123456/100.0)
'%02d:%02d:%02d.%02d' % [t.hour, t.min, t.sec, t.usec/10000]
#=> "01:20:34.56"

Upvotes: 2

Related Questions