How to make single digit number a two digit number in ruby?

老子叫甜甜 提交于 2019-12-04 17:50:20

问题


Time.new.month returns a single digit representation of any month prior to October (e.g. June is 6), but I want a 2-digit format (i.e. instead of 6 I want 06).

I wrote the following solution, and I am asking to see some other/better solutions.

s = 6.to_s; s[1]=s[0]; s[0] = '0'; s #=> '06'

回答1:


For your need I think the best is still

Time.strftime("%m")

as mentioned but for general use case the method I use is

str = format('%02d', 4)
puts str

depending on the context I also use this one which does the same thing:

str = '%02d %s %04d' % [4, "a string", 56]
puts str

Here is the documentation with all the supported formats: http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-sprintf




回答2:


You can use this printf-like syntax:

irb> '%02d' % 6
=> "06"

or

str = '%02d' % 6

So:

s = '%02d' % Time.new.month
=> "06"

See the documentation for String#%.




回答3:


Mat's answer pointing out that you can use the % operator is great, but I would like to point out another way of doing it, using the rjust method of the String class:

str = 6.to_s.rjust(2,'0')  # => "06"



回答4:


If you're trying to format an entire date or date and time (rather than just the month), you might want to use strftime:

m = Time.now.strftime('%m')
# => "06"
t = Time.now.strftime('%Y-%m-%dT%H:%M:%SZ%z')
# => "2011-06-18T10:56:22Z-0700"

That will give you easy access to all the usual date and time formats.




回答5:


You can use sprintf:

sprintf("%02d", s)

e.g. in irb:

>> sprintf("%02d", s)
=> "06"


来源:https://stackoverflow.com/questions/6397468/how-to-make-single-digit-number-a-two-digit-number-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!