Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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#?

like image 715
Gali Avatar asked Jun 30 '11 12:06

Gali


2 Answers

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.

like image 106
Jon Skeet Avatar answered Oct 21 '22 05:10

Jon Skeet


var result = string.Format("123{0}", number.PadLeft(9, '0'));
like image 29
jgauffin Avatar answered Oct 21 '22 05:10

jgauffin