C# Console => Formatting Strings and Integers

July 9, 2017 Oclemy C# Console, C# String, C# Integer 0 minutes, 54 seconds

A basic C# example for formatting strings.C# allows us to specify the placeholder for pieces of data whose values are not known until runtime.We use { } curly brackets.Then at runtime the passed values are substituted with their corressponding placeholders.

What we do :

  • Format and write strings according to placeholder value rather than position.
  • Format integers:
  • C or c is used to format currencies.Default is local currency.
  • D or d formats decimal numbers.May also specify minimum number of digits,like 9 below.
  • E or e formats exponential notation.
  • F or f for floating point formatting.May alo specify minimum digits like 3 below.
  • N or n for basic number formatting like having commas.

FORMAT STRINGS

using System;

namespace Example_A
{
    class Program
    {
        static void Main(string[] args)
        {
            //PRINT
            Console.WriteLine("Strings");
            Console.WriteLine("{0},{2},{1}","Zero","Two","One");

            Console.WriteLine("Integers");
           
            Console.WriteLine("c format: {0:c}", 10999);
            Console.WriteLine("f3 format: {0:f3}", 10999);
            Console.WriteLine("n format: {0:n}", 10999);
            Console.WriteLine("d9 format: {0:d9}", 10999);

            //READ INPUT B4 EXIT
            Console.ReadKey();

        }
    }
}

  RESULT Strings Zero,One,Two Integers c format: $10,999.00 f3 format: 10999.000 n format: 10,999.00 d9 format: 000010999

Comments