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

2019-02-12 06:20发布

问题:

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 formats as "+00"

i.ToString("00")

is close but does not add the + sign when the int is positive.

Is there any way to do this without explicit distinguishing between i >= 0 and i < 0?

回答1:

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



回答2:

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



回答3:

Try something like this:

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

Some examples:

Console.WriteLine((-99).ToString("+00;-00"));    // -99
Console.WriteLine(9.ToString("+00;-00"));        // +09
Console.WriteLine((-1).ToString("+00;-00"));     // -01
Console.WriteLine((0).ToString("+00;-00"));      // +00


标签: c# tostring