Hi Is there a quick way to add 0 to the beginning of a number if it only has one digit? ie 1 should be 01 11 should stay as 11 (These int''s can be transferred to a string) Thanks -- Posted via http://www.ruby-forum.com/.
On Tue, 2006-07-04 at 18:19 +0200, ben wrote:> Hi > > Is there a quick way to add 0 to the beginning of a number if it only > has one digit? > > ie > 1 should be 01 > 11 should stay as 11 > > (These int''s can be transferred to a string)---- have to be converted to a string to work... if my_var < 10 my_var = "0" + my_var.to_s else my_var = my_var.to_s end Craig
ben wrote:> Hi > > Is there a quick way to add 0 to the beginning of a number if it only > has one digit? > > ie > 1 should be 01 > 11 should stay as 11 > > (These int''s can be transferred to a string) > > Thanks > >If you need to "convert" them only for output, you should be able to use printf/ sprintf or format.. just use "%02d" as the format specifier for the number. Cheers Mohit.
sprintf "%02d", my_var or: format "%02d", my_var
On Tuesday, July 04, 2006, at 4:49 PM, orangegecko wrote:> >sprintf "%02d", my_var > >or: > >format "%02d", my_var >_______________________________________________ >Rails mailing list >Rails@lists.rubyonrails.org >http://lists.rubyonrails.org/mailman/listinfo/railsor "%02d" % my_var _Kevin -- Posted with http://DevLists.com. Sign up and save your mailbox.