How can I pad nullable ints with zeros?

流过昼夜 提交于 2019-12-25 06:56:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!