Number formatting

C

Cory

folks - can't quite figure this one out...

foo = 5
bar = 10


basically - when i go to print out the numbers - i want to format 'foo'
with a leding zero so that it reads '05' and is aesthetically pleasing
when compared to a double-digit number - such as bar: '10'.


essentially looking to get:

05
10
25
03
 
B

Brian Candler

folks - can't quite figure this one out...

foo = 5
bar = 10


basically - when i go to print out the numbers - i want to format 'foo'
with a leding zero so that it reads '05' and is aesthetically pleasing
when compared to a double-digit number - such as bar: '10'.


essentially looking to get:

05
10
25
03

foo = 5
puts "%02d" % foo


--------------------------------------------------------------- String#%
str % arg => new_str
------------------------------------------------------------------------
Format---Uses _str_ as a format specification, and returns the
result of applying it to _arg_. If the format specification
contains more than one substitution, then _arg_ must be an +Array+
containing the values to be substituted. See +Kernel::sprintf+ for
details of the format string.

"%05d" % 123 #=> "00123"
"%-5s: %08x" % [ "ID", self.id ] #=> "ID : 200e14d6"
 
L

Luis Parravicini

folks - can't quite figure this one out...

foo = 5
bar = 10

basically - when i go to print out the numbers - i want to format 'foo'
with a leding zero so that it reads '05' and is aesthetically pleasing
when compared to a double-digit number - such as bar: '10'.

Try using Kernel#printf.

irb(main):001:0> printf("%02d", 5)
05=> nil
 

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

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top