Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format integer to string with 5 digits

I need to have a string, based on an integer, which should always have 5 digits.

Example:

myInteger = 999
formatedInteger = "00999"

What is the best way of doing this in classic ASP?

like image 801
RSilva Avatar asked Nov 17 '08 11:11

RSilva


2 Answers

You can use string manipulation functions for this.

This assumes classic ASP with VBScript (original version of the answer).

Const NUMBER_DIGITS = 5

Dim myInteger
Dim formatedInteger

myInteger = 999
formatedInteger = Right(String(NUMBER_DIGITS, "0") & myInteger, NUMBER_DIGITS)

Here an optimized version, wrapped in a function, offering variable width padding:

Const NUMBER_PADDING = "000000000000" ' a few zeroes more just to make sure

Function ZeroPadInteger(i, numberOfDigits)
  ZeroPadInteger = Right(NUMBER_PADDING & i, numberOfDigits)
End Function

' Call in code:

strNumber = ZeroPadInteger(myInteger, 5)
like image 163
Tomalak Avatar answered Oct 13 '22 16:10

Tomalak


Something like this is what I've seen most of the time:

function PadNumber(number, width)
   dim padded : padded = cStr(number)

   while (len(padded) < width)
       padded = "0" & padded
   wend

   PadNumber = padded
end function

PadNumber(999, 5) '00999
like image 36
Jonathan Lonowski Avatar answered Oct 13 '22 18:10

Jonathan Lonowski