Ruby on Rails: How do you add add zeros in front of a number if it's under 10?

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

Solution 4 - Ruby on-Rails

Try this, it should work:

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

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

Solution 5 - Ruby on-Rails

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsjscView Question on Stackoverflow
Solution 1 - Ruby on-RailsRyan BiggView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMark RushakoffView Answer on Stackoverflow
Solution 3 - Ruby on-Railsax.View Answer on Stackoverflow
Solution 4 - Ruby on-RailsSalilView Answer on Stackoverflow
Solution 5 - Ruby on-RailsWashington BotelhoView Answer on Stackoverflow