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

前端 未结 3 878
忘掉有多难
忘掉有多难 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:43

    Try this:

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

    When separated by a semicolon (;) the first section will apply to positive values and zero (0), the second section will apply to negative values, the third section will apply to zero (0).

    Note that the third section can be omitted if you want zero to be formatted the same way as positive numbers. The second section can also be omitted if you want negatives formatted the same as positives, but want a different format for zero.

    Reference: MSDN Custom Numeric Format Strings: The ";" Section Separator

提交回复
热议问题