Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Control string and format specifiers

0 views
Skip to first unread message

Udi

unread,
Dec 6, 2005, 2:52:20 AM12/6/05
to
Hi,
I tried looking for it in the documentation but with no luck.
What's the equivalent C control strings in C# for the following:

"%3d" ? (space padding)
"%-3d" ? (left alignment)
"%+3d" ? (adding +/- sign)
"% 3d" ? (adding a space in case of positive vaklue)

(E.g - for zero padding - "%03d" is {0:d3}, but how do I do space
padding - "%3d"? )

I'll appreciate it if you can direct me to the relevant link.

Thanks!
Udi

Jon Skeet [C# MVP]

unread,
Dec 6, 2005, 3:04:34 AM12/6/05
to

If you look up "formatting strings" on MSDN, you'll find the "general"
rules for formatting, which includes alignment. So for the example you
gave, you need {0,3:d} for right alignment, and {0,-3:d} for left
alignment. You can also mix and match: {0,3:d2} will give " 05" for
instance.

Jon

Udi

unread,
Dec 6, 2005, 4:04:02 AM12/6/05
to
Thanks Jon, but this is the link I've looked at, however I didn't see
this notation {0,3:d2} anywhere.
Is there any equivalent for the "u" format specifier?
What if I have a 32 bit value that want to control the way it is
printed with the help of the format specifier just like in printf?
E.g. -
int i = -1;
printf("%u", i);

How do I do it in c#?
Thanks again for your time!
Udi.

Jon Skeet [C# MVP]

unread,
Dec 6, 2005, 4:42:16 AM12/6/05
to
Udi wrote:
> Thanks Jon, but this is the link I've looked at, however I didn't see
> this notation {0,3:d2} anywhere.

Well, it's the {index,alignment:formatString} notation - the d2 is the
formatString part, and the 3 is the alignment.

> Is there any equivalent for the "u" format specifier?
> What if I have a 32 bit value that want to control the way it is
> printed with the help of the format specifier just like in printf?
> E.g. -
> int i = -1;
> printf("%u", i);
>
> How do I do it in c#?

Do you mean you want to treat a signed integer as an unsigned integer?
It's not clear to me (not having done any C for a while) what you're
trying to do.

Jon

Udi

unread,
Dec 6, 2005, 4:48:02 AM12/6/05
to
yes, exactly.

say I have
int i = -1;

but I would like to print it as unsigned, meaning - in this case I'd
like WriteLine() to print the value of MAX_INT.
Is there a way to do it through the format specifiers? I.e. forcing the
value to be printed as unsigned?
Thanks!

Jon Skeet [C# MVP]

unread,
Dec 6, 2005, 4:57:47 AM12/6/05
to

Not that I know of, but why don't you just cast it to an unsigned int
in the first place?

Console.WriteLine ("{0:d}", (uint)i);

Jon

Udi

unread,
Dec 6, 2005, 7:02:25 AM12/6/05
to
Thanks Jon.
That's what I had in mind, just wanted to see if there's another way of
doing it to save the casting.
Udi.

0 new messages