Stripping or Adding Leading Zeros

A common dilemma is the need to either strip leading zeros or to have to add leading zeros back on to an Id or Medical Record Number. Here are two functions to handle these situations.

The first one provides you with the ability to add leading zeros in front of any string. You just have to send it the Id as a string and the end length you would like it to be. (In my example I will make it a 10 character number)

Here is the function:

function addZeros(Id, length)
   Id = string.rep('0', length-#Id)..Id
   return Id

The second function will remove all leading zeros in front no matter how many.:

function removeZeros(Id)
   while true do 
      if Id:sub(1,1) == '0' then 
         Id = Id:sub(2)
   return Id

If you would like to call these just to test them out then you can copy any paste the above functions at the bottom of your script and then use these two function calls from inside main:

   local Id1 = removeZeros('0004589787')
   local Id2 = addZeros('4589787', 10)

Leave A Comment?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.