问题
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.
回答1:
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")
回答2:
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');
回答3:
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
来源:https://stackoverflow.com/questions/27179656/how-can-i-pad-nullable-ints-with-zeros