# Add a zero on single digit numbers

**URL:** <https://www.ruby-forum.com/t/add-a-zero-on-single-digit-numbers/76452>\
**Category:** Ruby\
**Created:** [November 19, 2006, 2:01am UTC](https://www.ruby-forum.com/t/add-a-zero-on-single-digit-numbers/76452 "2006-11-19T02:01:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [November 19, 2006, 2:01am UTC](https://www.ruby-forum.com/t/add-a-zero-on-single-digit-numbers/76452/1 "2006-11-19T02:01:51Z")

</div>

Using DateTime.now.min I often get single digit numbers like “7”.  
However “22:7” isn’t really adequate for displaying time properly; I  
want “22:07”.

Is there any way add a 0 onto the front of a Fixnum?

I understand I could convert it into a string and add a zero onto the  
front of that string, but that’s not really ideal.

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [November 19, 2006, 2:11am UTC](https://www.ruby-forum.com/t/add-a-zero-on-single-digit-numbers/76452/2 "2006-11-19T02:11:53Z")

</div>

removed\_email\_address@domain.invalid wrote:

> Using DateTime.now.min I often get single digit numbers like “7”.  
> However “22:7” isn’t really adequate for displaying time properly; I  
> want “22:07”.
> 
> Is there any way add a 0 onto the front of a Fixnum?
> 
> I understand I could convert it into a string and add a zero onto the  
> front of that string, but that’s not really ideal.

check out DateTime#strftime.

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [November 19, 2006, 2:57am UTC](https://www.ruby-forum.com/t/add-a-zero-on-single-digit-numbers/76452/3 "2006-11-19T02:57:56Z")

</div>

On Sun, Nov 19, 2006, removed\_email\_address@domain.invalid wrote:

> Is there any way add a 0 onto the front of a Fixnum?

Sure:

num = 7  
printf(’%02d’, num)

You can use #sprintf instead if you want to assign that back to a  
variable.

That said, Timothy’s suggestion of using #strftime is a much better  
solution to your problem… it’s just valuable to know about #(s)printf  
in general.

Ben
