[noob question] convert 7 in 07

P

Paul A.

Hi,

I would like to display numbers with a 0 before when there is only one
char.
For exemple if I gets the number 4, I would like to return 04.

After looking methods on
http://www.ruby-doc.org/core/classes/Fixnum.html, I don't see how to
process. Of cours it is possible to convert a number into string and
after add a 0, but it's not very friendly.

Thanks for ideas
 
R

Robert Klemme

2009/4/22 Paul A. said:
I would like to display numbers with a 0 before when there is only one
char.
For exemple if I gets the number 4, I would like to return 04.

After looking methods on
http://www.ruby-doc.org/core/classes/Fixnum.html, I don't see how to
process. Of cours it is possible to convert a number into string and
after add a 0, but it's not very friendly.

Please look up sprintf, printf and String#%.

Cheers

robert
 
M

Marc Heiler

counter = 1; sprintf("%02d", counter) # => "01"

In general, the ruby String class is much better than Int class -
because Strings are like everywhere in ruby. I believe Matz once said
that the String class was most work (or devoured most manhours when he
worked on ruby initially)
 
R

Rimantas Liubertas

I would like to display numbers with a 0 before when there is only one
Please look up sprintf, printf and String#%.

And keep in mind that you will have to convert to string anyway,
because while 07 is fine
08 and 09 are illegal in Ruby=E2=80=94it treats numbers with leading zero a=
s
octal numbers:
SyntaxError: (irb):4: Invalid octal digit from /usr/local/bin/irb:12:in `<m=
ain>'

Regards,
Rimantas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,491
Latest member
mohitk

Latest Threads

Top