Sham
Sham

Reputation: 840

How to Prefix '0' (zero) to integer value

I have a situation where I need to prefix a zero to an integer. Initially I have string which has 12 chars, first 7 are alphabets and 5 are numeric values. The generated string some times have a zero at starting position of numeric values. for example ABCDEF*0*1234, and my scenario is to generate a range of strings from the generated string. Suppose I want to generate a range (assume 3 in number), so it would be ABCDEF01235, ABCDEF01236, ABCDEF01237.

When I try to convert a string which has a 0 (as shown above) to int, it returns only 1234. Is there any way to do this, without truncating zero?

Upvotes: 5

Views: 9973

Answers (5)

Koycho Drekov
Koycho Drekov

Reputation: 1

int num = 1234;
Console.WriteLine($"{num:d5}");

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102793

You can use PadLeft to expand a given string to a given total length:

int num = 1234;
Console.WriteLine(num.ToString().PadLeft(5, '0'));  // "01234"

Upvotes: 9

Simon Hughes
Simon Hughes

Reputation: 3574

 int num = 1234;
 Console.WriteLine(num.ToString("D5"));  // "01234"

Upvotes: 7

leon_ALiang
leon_ALiang

Reputation: 79

I think you can use string.Format

    int num = 1234;
    Console.WriteLine(string.Format("0{0}", num));

Upvotes: -1

Gianni B.
Gianni B.

Reputation: 2731

No with int.

You have to use string to concatenate the parsed number and the 0

Upvotes: 0

Related Questions