Leading zeros - Number Formatting

I was just googling to see if there was any information on presenting
numeric fields with leading zeros, but have found no discussion either
here or in the wiki.

In my app, I would like to display leading zeros on id fields that are
used as external user references. eg. customer.id or order.id etc -
both in forms and in table/text entries. To give a fixed sized number
eg. 5 digits.

Does anyone have any clever solutions. One way to do it would be to
use a method call such as:

pad(ref_id,5) etc.

The other approach is to put an entry in the model to provide the
ref_id as a padded string.

def p_ref_id

length=id.to_s.length
padded_id=‘0’ * (5-length) + id.to_s unless length>5

end

I am using MySQL which allows id fields to be zero filled, but this
doesnt seem to help, and also there is the lpad(id,0,5) function, but I
am not sure it would make sense to try and use this from within rails.

I just wondered if there is anything already built into rails that I am
overlooking, or if there is a better approach - Any thoughts?

Tony

Just noticed my timebomb in the padding method. It should be:

def p_ref_id

length=id.to_s.length

if length > 4 then
id.to_s
else
padded_id=‘0’ * (5-length) + id.to_s
endif
end

tonypm wrote:

I was just googling to see if there was any information on presenting
numeric fields with leading zeros, but have found no discussion either
here or in the wiki.

I just use string formatting - e.g.

“%05d” % an_int

if an_int = 123 it will give you the string “00123”

Cheers

Ian

Thanks that helps.

tonypm wrote:

Thanks that helps.

I can use it, but I have just realised I dont really know how it works!
I have been looking at % in ruby but cannot relate it to this
solution?. I would really appreciate a pointer.

On 9/22/06, tonypm [email protected] wrote:

Hi Tony,

The documentation is here;

http://www.ruby-doc.org/core/classes/String.html#M001446
http://www.ruby-doc.org/core/classes/Kernel.html#M002001

Cheers,
Dave

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs