471,355 Members | 1,641 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,355 software developers and data experts.

Right-align a number?

Hi,

Can I right-align a number with leading *spaces*?
F.i. I have the value 2 and I want to display it as " 2".

int num = 2;
string s = num.ToString("00"); // gives "02", but I don't want the "0"
s = num.Tostring("#0"); // gives "2" - no leading space

s = num.ToString().PadLeft(2); // works, but is a bit cumbersome.

Also, how can I do this in a "format-string"?
s = String.Format("{0:00}", num); // gives "02"
s = String.Format("{0:#0}", num); // gives "2"
Hans Kesting
Jan 18 '06 #1
2 16827
Hans Kesting wrote:
Can I right-align a number with leading *spaces*?


Yes. Use the alignment component. In your case, you'd want
string.Format ("{0,2}", num);

(Making the alignment negative left-aligns it instead.)

Jon

Jan 18 '06 #2
> Hans Kesting wrote:
Can I right-align a number with leading *spaces*?


Yes. Use the alignment component. In your case, you'd want
string.Format ("{0,2}", num);

(Making the alignment negative left-aligns it instead.)

Jon


You are right (as usual), thanks.
I couldn't find it in the "Formatting Overview" section and had missed
the remark in the String.Format section, where it is described.

Hans Kesting
Jan 18 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by Bo Wisén | last post: by
22 posts views Thread by Marek Mand | last post: by
2 posts views Thread by Dr. Richard E. Hawkins | last post: by
22 posts views Thread by Simon | last post: by
3 posts views Thread by deanfamily11 | last post: by
19 posts views Thread by ashkaan57 | last post: by
22 posts views Thread by ashkaan57 | last post: by
12 posts views Thread by Dio1080 | last post: by
reply views Thread by XIAOLAOHU | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.