Force an Integer To Be At Least 2 Digits Long [closed]
Can someone give me code to do the following....
if the integer is 1-9 display a string 01,02,03 etc.. if 10 or over leave it as is.
string display = yourInt.ToString("00");
DOES NOT WORK
string display = yourInt.ToString("00");
Or, in String.Format
syntax (used in Console.WriteLine
, for example)
string s = String.Format("{0:00}", yourInt);
I don't see why .ToString("00")
didn't work. This test succeeds...
[TestMethod]
public void RightPadIntegersWithZero() {
var values = new [] { -100, -20, -1, 0, 1, 5, 10, 100, 567 };
var expecteds = new [] { "-100", "-20", "-01", "00", "01", "05", "10", "100", "567" };
for (var i = 0; i < values.Length; i++) {
var value = values[i];
var expected = expecteds[i];
var result = value.ToString("00");
Assert.AreEqual(expected, result);
}
}
You must be doing something different than what your question describes
In any language (at least the ones i know) and integer value type will never have 2
digits length in any value below 10
.
To display it with always a two digits length (as 02
, 05
, 12
) you must convert your number to String and then padding
it with 0
.
Or you will evaluate it like:
String newValue = String.Format("{0:00}", yourInt);
As you see you will have to convert it to string before displaying it...
Your question is a bit ambiguous: display it where?
In any case, you will probably want to look at String.Format.
Would this do what you want?
for (int i = -20; i < 100; i++)
{
string s = i.ToString();
while (s.Length < 2) s = "0" + s;
Console.WriteLine(s);
}
I realize it's a bit of a brute force approach as written here. But if it did the trick, you could optimize it with a reusable character array instead of appending the string.
精彩评论