Determine Number of Digits and Pad with 0 when required [C#]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
Given a string strTotal (all numerical values).

I need a mechanism to do the following.
1- Determine the number of digits in strTotal
2- If there are less then 2 (digits 0 to 9) then pad with a 0 to form 2-Digit Values like 00, 01, 02, 03,…, 08, 09.
Else leave as-is.

Any clues?
 
Shaitan00 said:
Given a string strTotal (all numerical values).

I need a mechanism to do the following.
1- Determine the number of digits in strTotal
2- If there are less then 2 (digits 0 to 9) then pad with a 0 to form 2-Digit Values like 00, 01, 02, 03,…, 08, 09.
Else leave as-is.

Any clues?

Something like:

public string PaddedNumber(object oOriginal)
{
if (oOriginal.ToString().Length == 1)
{
return oOriginal.ToString().PadLeft(1, '0');
}
else
return oOriginal.ToString();
}
 
Originally Posted by Shaitan00
Given a string strTotal (all numerical values).

I need a mechanism to do the following.
1- Determine the number of digits in strTotal
2- If there are less then 2 (digits 0 to 9) then pad with a 0 to form 2-Digit Values like 00, 01, 02, 03,…, 08, 09.
Else leave as-is.

Any clues?

Try this:

for (int i = 0; i < strTotal.Length; i++)
{
if (i < 10)
{
Response.Write("0" + strTotal);
}
else
{
Response.Write(strTotal);
}
}
 
I personally would use PadLeft, like Jaco, but the first parameter should be a two (for a total minimum of two characters), not a one, and there is no need to check the length of the string. All of this is assuming that your string contains a single, properly formatted integer.
 
The algorithm that doesn't....

Algorithm's algorithm isn't just inferior, it is completely useless.

If strTotal is "1", we get:
01

If strTotal is "12", we get:
012012


If strTotal is "1234567890", we get:
0123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678901234567890

:rolleyes:
 
could you not use .ToString("00") to return the number as a string? i.e. the following would product output like
Code:
00
01
02
...
08
09
10
11
12
13
...
98
99
100

C#:
for(int i=0;i <= 100;i++)
    Debug.WriteLine((i.ToString("00")));
 
Back
Top