Forum: Ruby on Rails Formatting integer (2 printed as 02)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Brij N. (Guest)
on 2007-03-29 02:50
Hi,

I want to format an integer as hours and minutes.

Of course it's easy to write this myself, but let's respect DRY!

Is there a method I can use so that integers are converted to strings of
2 digits?

So:
2 --> 02
11 --> 11
4 --> 04

thanks!
Thiago J. (Guest)
on 2007-03-29 03:10
(Received via mailing list)
Yep, you can use sprintf:

>> sprintf("%0.2d", 4)
=> "04"

--
Thiago J.
acts_as_solr => http://acts-as-solr.rubyforge.org
Sitealizer Web Stats => http://sitealizer.rubyforge.org


On Mar 28, 3:50 pm, Brij N. <removed_email_address@domain.invalid>
Philip H. (Guest)
on 2007-03-29 03:18
(Received via mailing list)
> 4 --> 04
sprintf("%02d", 4) => 04

-philip
Eden L. (Guest)
on 2007-03-29 06:56
(Received via mailing list)
also,

>> i=61; "%02i:%02i" % [i / 60, i % 60]
=> "01:01"

On Mar 29, 6:50 am, Brij N. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.