Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 289
Francisco A. Avatar asked Sep 12 '25 08:09

Francisco A.


1 Answers

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.

like image 192
Michael Goldshteyn Avatar answered Sep 14 '25 22:09

Michael Goldshteyn