Search code examples
c#string-length

Padding string with 0's -- formatting style?


Ok, so I need to pad a string value with a certain number of 0s depending on whether the string is 6 characters in length or not. But the resulting value must be no more than 6 characters.

For example:

  • 123 should be changed to 000123
  • 4567 should be changed to 004567
  • 123456 should not be changed at all

What I have set up right now does not work, unfortunately. It only changed the inputed string value to be D6. (Note: The value of NMFCItemNum can be empty--in those cases, nothing needs to be done).

I have figured out that D# gives the appropriate amount of 0's before a value but the setup is wrong.

            string NMFCItemNum = GetValue(curCategory, (int)CategoryCols.NMFCItemNum);
            if (NMFCItemNum != "")
            {
                //Save the value of NMFCItemNum as is
                if (NMFCItemNum.Length == 6)
                {
                    cmd.Parameters.Add(new SqlParameter("@NMFCItemNumber", GetValue(curCategory, (int)CategoryCols.NMFCItemNum)));
                }
                else
                {
                    if (NMFCItemNum.Length < 6)
                    {
                        //prefix with 0's then save to database
                        cmd.Parameters.Add(new SqlParameter("@NMFCItemNumber", String.Format("D6",NMFCItemNum)));
                    }
                }
            }

Solution

  • You can use the string.PadLeft(Total Width, character) method

    NMFCItemNum.PadLeft(6, '0');