Number formatting with leading spaces

M

MrAsm

Hi,

what is (if exist) the format string to print an integer in C# with
leading spaces (to do right justification) e.g.

value = 77

|<----->| <--- width = 5 characters
+ 12345 +
| |
| 77 |
^^^
3 leading spaces


Thanks
MrAsm
 
F

Frank Werner

Hello MrAsm,

this should help:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Value:" + formatInt(77, 5));
Console.Read();
}
private static string formatInt(int intVal, int intTotalsize)
{
string retVal = "";
if (intVal.ToString().Length < intTotalsize)
{
for (int slice = 0; slice < intTotalsize - intVal.ToString().Length;
slice++)
{
retVal = retVal + " ";
}
retVal = retVal + intVal.ToString();
}
else
{
retVal = intVal.ToString();
}
return retVal;
}
}
}


Regards

Frank
 
C

Chris Dunaway

Thank you very much for your code, Frank.

MrAsm

Why not use the String.Format? It's what it is designed for:

Console.WriteLine(String.Format({0,5}, 77));

This is similar to the C printf method. The {0,5} is a placeholder.
The 0 indicating it is the first argument in the list of items to be
formatted (77 in this case). The ,5 indicates that the field is
padded to 5 characters, right justified. For left justified you would
use -5. You can also add an option format string after the 5. See
the following link for more information:

http://msdn2.microsoft.com/en-us/library/fht0f5be.aspx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top