How to force a sign when formatting an Int in c#

前端 未结 3 877
忘掉有多难
忘掉有多难 2021-01-04 06:02

I want to format an integer i (-100 < i < 100), such that:

-99 formats as \"-99\"
9 formats as \"+09\"
-1 formats as \"-01\"
0 forma

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-04 06:36

    You might be able to do it with a format string like so..

    i.ToString("+00;-00");
    

    This would produce the following output..

    2.ToString("+00;-00");    // +02
    (-2).ToString("+00;-00"); // -02
    0.ToString("+00;-00");    // +00
    

    Take a look at the MSDN documentation for Custom Numeric Format Strings

提交回复
热议问题