Robb Hoff
Robb Hoff

Reputation: 1910

In C#, how can I format integers with zero-padding without making negative values longer?

I'm working in C# .Net 5.0, Visual Studio. I'm formatting integers to have zero-padding like so

$"{-1:d04}"
$"{1:d04}"

Formatting positive and negative numbers give different lengths of the resulting strings

-0001
0001

I need my numbers to be the same length (i.e. the result in this example should be the strings "-001" and "0001"), does there exist any formatting pattern to achieve this?

Upvotes: 4

Views: 1015

Answers (1)

Sweeper
Sweeper

Reputation: 271410

One way is to use the ; specifier to provide two formats for non-negative and negative numbers.

int x = 1;
Console.WriteLine($"{x:0000;-000}"); // "0001"
x = -1;
Console.WriteLine($"{x:0000;-000}"); // "-001"

0000 for positive numbers, -000 for negative numbers.

This does mean that you no longer use the standard format specifier D, which automatically uses the NegativeSign from the current NumberFormatInfo. You'd have to hardcode the negative sign in. This may or may not be a problem depending on what you are doing.

Edit:

Apparently this is for sorting strings. If the format doesn't have to be exactly "0001" and "-001", and just has to be the same length, then I suggest:

int x = 1;
Console.WriteLine($"{x,5:d04}"); // " 0001" (note the leading space)
x = -1;
Console.WriteLine($"{x,5:d04}"); // "-0001"

Upvotes: 7

Related Questions