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.
17bac6badac4918e91443194b8188e65?d=identicon&s=25 Brij Naald (brijnaald)
on 2007-03-29 00: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!
Ed2af9abb16c6d3c9f5d07cd8f2c8ffd?d=identicon&s=25 Thiago Jackiw (Guest)
on 2007-03-29 01:10
(Received via mailing list)
Yep, you can use sprintf:

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

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


On Mar 28, 3:50 pm, Brij Naald <rails-mailing-l...@andreas-s.net>
2f9a03aa0fcfe945229cb6126eda2cb2?d=identicon&s=25 Philip Hallstrom (Guest)
on 2007-03-29 01:18
(Received via mailing list)
> 4 --> 04
sprintf("%02d", 4) => 04

-philip
8bc543795b502900b5333aea73ad5533?d=identicon&s=25 Eden Li (edenli)
on 2007-03-29 04:56
(Received via mailing list)
also,

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

On Mar 29, 6:50 am, Brij Naald <rails-mailing-l...@andreas-s.net>
This topic is locked and can not be replied to.