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

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.

Hi Tony,

The documentation is here;

    Class: String (Ruby 3.1.2)     Module: Kernel (Ruby 3.1.2)

Cheers, Dave