Francisco A.
Francisco A.

Reputation: 43

How do I print a formatted number to the screen in C#?

I am trying to format a matrix in C# as shown:

 1  2
10 11

I could do this in C using:

printf("%2d",number)

Is there a similar command in C#? I have tried String.Format and ToString, but I can't figure out how to make them do what I want. I am just starting out in C#, so any suggestions would be appreciated.

Upvotes: 4

Views: 3820

Answers (1)

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74330

This is equivalent to a %2d for printf, in C#:

string s=string.Format("{0,2}",number);

The number after the comma right aligns if positive and left aligns if negative, to the specified number of total characters (including the number itself).

Here is a link to a helpful site with a guide on how to format integers in various ways that may help you with the rest of your problem.

Upvotes: 5

Related Questions