Question

I want to convert a string which contains 5 zeros ("00000") into a Int so it can be incremented. Whenever I convert the string to an integer using Convert.ToInt32(), the value becomes 0. How can I ensure that the integer stays at a fixed length once converted?

I want to be able to increment the value from "00000" to "00001" and so on so that the value appears with that many digits in a database instead of 0 or 1.

If you are going to down vote question, the least you could do is leave feedback on why you did it...

Was it helpful?

Solution

An integer is an integer. Nothing more.

So the int you have has value zero, there is no way to add any "length" metadata or similar.

I guess what you actually want is, that - at some point - there will be a string again. You want that string to represent your number, but with 5 characters and leading zeroes.

You can achieve that using:

string s = i.ToString("00000")

EDIT

You say you want the numbers to appear like that in your DB. Ask yourself:

Does it really need to be like that in the DB or is it sufficient to format the numbers as soon as you read them from the database?

Depending on that, format them (as shown above), either when writing to or reading from the DB. Of course, the former case will require more storage space and you cannot really use SQL or similar to perform arithmetic operations!

OTHER TIPS

An integer doesn't have a length, it's purely a numerical value. If you want to keep the length, you have to store the information about the length somewhere else.

You can wrap the value in an object that keeps the length in a property. Example:

public class FormattedInt {

  private int _value, _length;

  public FormattedInt(string source) {
    _length = source.Length;
    _value = Int32.Parse(source);
  }

  public void Increase() {
    _value++;
  }

  public override string ToString() {
    return _value.ToString(new String('0', _length));
  }

}

Usage:

FormattedInt i = new FormattedInt("0004");
i.Increase();
string s = i.ToString(); // 0005

As olydis says above, an int is just a number. It doesn't specify the display format. I don't recommend storing it padded out with zeroes in a database either. It's an int, store it as an int.

For display purposes, in the app, a report, whatever, then pad out the zeroes.

string s = i.ToString("00000");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top