How do I add "123" to the beginning of a string and pad it to be exactly 12 chars?

58,944

Solution 1

Well, you could use:

string result = "123" + text.PadLeft(9, '0');

In other words, split the task in half - one part generating the "000028431", "000000987" etc part using string.PadLeft, and the other prefixing the result with "123" using simple string concatenation.

There are no doubt more efficient approaches, but this is what I'd do unless I had a good reason to believe that efficiency was really important for this task.

Solution 2

var result = string.Format("123{0}", number.PadLeft(9, '0'));

Solution 3

You could try:

var str = String.Format("123{0:0#########}", 28431);

or

var str = String.Format("123{0:000000000}", 28431);

Solution 4

Assuming...

  1. The strings are known to always contain representations of decimal integers.
  2. The represented integer is always less than 109.

...you could do this:

(123000000000 + long.Parse(s)).ToString()

Solution 5

Well, if you have numbers less than 1000000000, you could just add 123000000000 to each number.

Share:
58,944
Gali
Author by

Gali

Updated on September 24, 2020

Comments

  • Gali
    Gali over 3 years

    I need to add "123" and zeros for any string - but the resulting string must be exactly 12 characters long.

    For example:

    28431 = 123000028431
    987   = 123000000987
    2     = 123000000002
    

    How to do this in C#?

  • Rabeel
    Rabeel almost 13 years
    The values are strings, not a numeric type.
  • Narnian
    Narnian almost 13 years
    Ah... ok... I just assumed they were numeric since that was what the examples were. Looks like there are other good answers.
  • Jethro
    Jethro almost 13 years
    Lol, I was about to ask you how efficient that approach was, I guess it's only going to be called once or twice so doesn't really matter. :)
  • jgauffin
    jgauffin almost 13 years
    I bet that there are a dozen other places in any application which will be more ineffecient than this code snippet.