CSharp String.Format, howto pad numbers with zeros

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • davesf
    New Member
    • Feb 2012
    • 1

    CSharp String.Format, howto pad numbers with zeros

    I stumbled upon this question about padding with zeros in csharp. Since it's locked and doesn't have the best answer, I decided to post this article..



    This page lists the string formatting operators valid as ToString arguments. While it's not obvious, these are all also valid in String.Format()

    In this article, learn to use standard numeric format strings to format common numeric types into text representations in .NET.


    Therefore, if this is what you need:

    Input number Need
    1 00000001
    121 00000121
    10567 00010567

    You can get it by doing:

    String.Format(" {0:D8}",1);
    String.Format(" {0:D8}",121);
    String.Format(" {0:D8}",10567);
  • RhysW
    New Member
    • Mar 2012
    • 70

    #2
    Feel i should also point out this is useful for snipping off the ends of ridiculously long decimal numbers too if properly used, simple yet effective piece of code

    Comment

    • PsychoCoder
      Recognized Expert Contributor
      • Jul 2010
      • 465

      #3
      You could also use String.PadRight and String.PadLeft for this.

      Comment

      Working...