C# - increment number and keep zeros in front
Asked Answered
W

5

17

I need to make a 40 digit counter variable. It should begin as 0000000000000000000000000000000000000001
and increment to
0000000000000000000000000000000000000002

When I use the int class, it cuts off all the zeros. Problem is I need to increment the number and then convert it to a string, with the correct number of leading zeros. The total size should be 40 digits. So if I hit 50 for example, it should look like this:

0000000000000000000000000000000000000050

How can I do that and retain the zeros?

Whalen answered 7/6, 2012 at 15:33 Comment(1)
You'll be needing to use something more like BigInteger rather than int, otherwise the increment will fail in short order.Mural
P
39

Use the integer and format or pad the result when you convert to a string. Such as

int i = 1;
string s = i.ToString().PadLeft(40, '0');

See Jeppe Stig Nielson's answer for a formatting option that I can also never remember.

Propagandism answered 7/6, 2012 at 15:35 Comment(1)
@RhysW, no, it simply pads to the length you specify with the character also specified. It will not exceed that length. For example, "123".PadLeft(2, '0') will simply return "123"Propagandism
S
20

Try using

int myNumber = ...;
string output = myNumber.ToString("D40");

Of course, the int can never grow so huge as to fill out all those digit places (the greatest int having only 10 digits).

Sandbag answered 7/6, 2012 at 15:36 Comment(0)
F
2

Just convert your string to int, perform the addition or any other operations, then convert back to string with adequate number of leading 0's:

// 39 zero's + "1"
string initValue = new String('0', 39) + "1";

// convert to int and add 1
int newValue = Int32.Parse(initValue) + 1;

// convert back to string with leading zero's
string newValueString = newValue.ToString().PadLeft(40, '0');
Fabre answered 7/6, 2012 at 15:47 Comment(0)
L
2

I had to do something similar the other day, but I only needed two zeros. I ended up with

string str = String.Format("{0:00}", myInt);

Not sure if it's fool proof but try

String.Format("{0:0000000000000000000000000000000000000000}", myInt)
Lesley answered 7/6, 2012 at 15:53 Comment(0)
S
0

You can use this too..

int number = 1;
string tempNumber = $"{number:00}";

result:

01
Surpassing answered 14/4, 2020 at 1:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.