Creating Custom Formats - CSharp Language Basics

CSharp examples for Language Basics:Data Type Format

Introduction

SpecifierDescription
0Zero placeholder. Filled with digit, if available.
#Blank placeholder. Filled with digit, if available.
.Displays a period. Used for decimal points.
,Uses a comma for separating groups of numbers.
%Displays the number as a percentage value (for example, 1.00 is 100%).
\Used to indicate that a special character should be printed. This can be one of the escape characters, such as the newline character (\n).
'xyz'Displays text within the apostrophes.
"xyz"Displays text within the quotes.

Demo Code

using System;/*from w ww  .ja  v  a 2  s .  c om*/
class Picts
{
   public static void Main()
   {
      int var1 = 1234;
      float var2 = 12.34F;
      // Zero formatter
      Console.WriteLine("\nZero...");
      Console.WriteLine("{0} -->{0:0000000}", var1);
      Console.WriteLine("{0} -->{0:0000000}", var2);
      // Space formatter
      Console.WriteLine("\nSpace...");
      Console.WriteLine("{0} -->{0:0####}<--", var1);
      Console.WriteLine("{0} -->{0:0####}<--", var2);
      // Group separator and multiplier (,)
      Console.WriteLine("\nGroup Multiplier...");
      Console.WriteLine("{0} -->{0:0,,}<--", 1000000);
      Console.WriteLine("Group Separator...");
      Console.WriteLine("{0} -->{0:##,###,##0}<--", 2000000);
      Console.WriteLine("{0} -->{0:##,###,##0}<--", 3);
      // Percentage formatter
      Console.WriteLine("\nPercentage...");
      Console.WriteLine("{0} -->{0:0%}<--", var1);
      Console.WriteLine("{0} -->{0:0%}<--", var2);
      // Literal formatting
      Console.WriteLine("\nLiteral Formatting...");
      Console.WriteLine("{0} -->{0:'My Number: '0}<--", var1);
      Console.WriteLine("{0} -->{0:'My Number: '0}<--", var2);
      Console.WriteLine("\n{0} -->{0:Mine: 0}<--", var1);
      Console.WriteLine("{0} -->{0:Mine: 0}<--", var2);
   }
}

Result


Related Tutorials