Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Number formatting

Reply
Thread Tools

Number formatting

 
 
Cory
Guest
Posts: n/a
 
      05-31-2007
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

--
Posted via http://www.ruby-forum.com/.

 
Reply With Quote
 
 
 
 
Brian Candler
Guest
Posts: n/a
 
      05-31-2007
On Fri, Jun 01, 2007 at 01:03:26AM +0900, Cory wrote:
> 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"



 
Reply With Quote
 
 
 
 
Luis Parravicini
Guest
Posts: n/a
 
      05-31-2007
On 5/31/07, Cory <(E-Mail Removed)> wrote:
> 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


--
Luis Parravicini
http://ktulu.com.ar/blog/

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
OT: Number Nine, Number Nine, Number Nine FrisbeeŽ MCSE 37 09-26-2005 04:06 PM
Number Formatting Question C# probashi ASP .Net 4 02-23-2005 03:55 PM
Formatting decimal number Luis Esteban Valencia ASP .Net 1 01-12-2005 02:13 PM
Number formatting rguti ASP .Net 1 06-10-2004 06:46 PM
Need formatting options menu for formatting hard drive Mark T. Computer Support 3 11-24-2003 11:50 PM



Advertisments