Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

tostring

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?

like image 839
willem Avatar asked Mar 14 '11 16:03

willem


People also ask

What does %3f mean in C?

number", and has slightly different meanings for the different conversion specifiers (like d or g). For floating point numbers (e.g. %f), it controls the number of digits printed after the decimal point: 1. printf ( "%.3f" , 1.2 ); will print.

What is string formatting in C?

The Format specifier is a string used in the formatted input and output functions. The format string determines the format of the input and output. The format string always starts with a '%' character.


1 Answers

Try this:

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

When separated by a semicolon (;) the first section will apply to positive values, 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

like image 148
squillman Avatar answered Sep 19 '22 03:09

squillman