131

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?

1

5 Answers 5

215

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 long and pad it with '0'. ljust does the opposite.

2
  • 2
    This is only better than sprintf if you want to allow strings. Otherwise I'd use sprintf, since it throws an exception (like it should) if I accidentally use a string. Jan 9, 2015 at 16:23
  • If you know you're starting with a string representation of a number, I like this better than sprintf for performance. Using rjust avoids the cost of parsing sprintf's format string, converting a string to a number, and converting that number back to a string. Plus, it's (arguably) easy for a human to understand what the code is trying to do at a glance. Jul 26, 2019 at 15:43
157

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).

2
  • 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
    Apr 23, 2010 at 4:21
  • 1
    you can simply '%02d'%1 without sprintf Apr 19, 2019 at 5:50
35

how about "%02d" % 9? see http://www.ruby-doc.org/core-2.0/String.html#method-i-25 and http://www.ruby-doc.org/core-2.0/Kernel.html#method-i-sprintf .

0
12

Try this, it should work:

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

abc = 5.0
puts "%.2f" % abc # => 5.00
2
2

Rubocop recommends format over sprintf and %. I think it's more intuitive:

format('%02d', 7) # => "07"
format('%02d', 12) # => "12"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.