views:

173

answers:

5

I'm looking to convert single digit numbers to two-digit numbers like so:

9 ==> 09
5 ==> 05
12 == 12
4 ==> 04

I figure I could put a bunch of if-else statements (if number is under 10, then do a gsub) but figure that's horrible coding. I know Rails has number_with_precision but I see that it only applies to decimal numbers. Any ideas on how to convert single-digits to two-digits?

A: 

there is no language that supports numbers with leading zero. You need to convert number to string and if < 10 add 0 in front of it.

TriLLi
Thank you TriLLi. I see that there might be a solution on this page API (http://www.ruby-doc.org/core/classes/String.html#M001446), which says that you can do something like this:"%05d" % 123 #=> "00123"Could that be one way to do it?
sjsc
And precisely *how* could he do that? Try to be more helpful rather than giving advice like this.
Ryan Bigg
+6  A: 

Did you mean sprintf '%02d', n?

irb(main):003:0> sprintf '%02d', 1
=> "01"
irb(main):004:0> sprintf '%02d', 10
=> "10"

You might want to reference the format table for sprintf in the future, but for this particular example '%02d' means to print an integer (d) taking up at least 2 characters (2) and left-padding with zeros instead of spaces (0).

Mark Rushakoff
Thank you Mark!! Perfect =) Thank you!
sjsc
You should probably use `%02i` for this case as it is more obvious that the output is and is supposed to be an integer, d is less intuitive for people who are not as accustomed to using `sprintf`.
SeanJA
+8  A: 

how about "%02d" % 9? see http://www.ruby-doc.org/core/classes/String.html#M000770 and http://www.ruby-doc.org/core/classes/Kernel.html#M005962 .

ax
Thank you ax! That works perfectly =) Thank you so much!
sjsc
+1 for using `sprintf` shortcut
macek
+1  A: 

TRY THIS IT SHOULD WORK

abc= 5
puts "%.2i" %abc   >> 05


abc= 5.0
puts "%.2f" %abc   >> 5.00
Salil
I WILL TRY IT IF YOU STOP SHOUTING
SeanJA
A: 

A lot of people using sprintf (which is the right thing to do), and I think if you want to do this for a string it's best to keep in mind the rjust and ljust methods:

"4".rjust(2, '0')

This will make the "4" right justified by ensuring it's at least 2 characters width and to pad it with '0'. ljust does the opposite.

Ryan Bigg