Right-align a number?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Hans Kesting

    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("0 0"); // 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


  • Jon Skeet [C# MVP]

    #2
    Re: Right-align a number?

    Hans Kesting wrote:[color=blue]
    > Can I right-align a number with leading *spaces*?[/color]

    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

    Comment

    • Hans Kesting

      #3
      Re: Right-align a number?

      > Hans Kesting wrote:[color=blue][color=green]
      >> Can I right-align a number with leading *spaces*?[/color]
      >
      > 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[/color]

      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


      Comment

      Working...