How can I pad nullable ints with zeros?

583 Views Asked by At

Is there any way to pad nullable int with zeros the way you can with normal int?

the myInt.ToString("D3") doesn't seem to work on nullale ints but for my current project I feel like I need to use nullable int in order to get the null value in my array instead of 0 as the default.

3

There are 3 best solutions below

2
On

You have to perform that action on the value:

myInt.Value.ToString("D3")

Example:

int? myInt = 3;
Console.WriteLine(myInt.Value.ToString("D3")); // Outputs 003
0
On

An int has never leading zeros, it just has a value. A string representation of an ìnt can have them. You can use the null-coalescing operator to convert the nullable-int to 0 if it has no value:

int? nullableInt = null;
string number = (nullableInt ?? 0).ToString("D3"); // 000

or use String.PadLeft:

number = (nullableInt ?? 0).ToString().PadLeft(3, '0');
0
On

That is because int? is actually Nullable<T> where T is int here.

Calling ToString will call that on the Nullable struct, not the int. Nullable<T> has no knowledge of the overloads of ToString which int has.

You have to get the integer value first:

myInt.GetValueOrDefault(0).ToString("D3")