-3

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)));
                    }
                }
            }
Dejsa Cocan
  • 1,539
  • 3
  • 19
  • 56
  • @Prix, this wouldn't be a duplicate if the question were about the error with the formatting string. OP, consider re-wording if you still want to use `String.Format`. – BradleyDotNET Jan 15 '15 at 19:03

3 Answers3

1
String.Format("D6",NMFCItemNum)

Has "D6" as a simple string. A formatting string interprets "D6" as just that, "D6". You need to use a placeholder:

String.Format("{0:D6}", NMFCItemNum);

Says "Take the first argument, stuff it into the {0} place, and use "D6" formatting.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

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

NMFCItemNum.PadLeft(6, '0');

Saggio
  • 2,212
  • 6
  • 33
  • 50
1

Something like this?

string str = "1234"
Console.WriteLine(str.PadLeft(8, '0'));  
//00001234
Ivan Crojach Karačić
  • 1,911
  • 2
  • 24
  • 44