Monday, May 3, 2021

C# String Format

using System;

namespace ConsoleStringFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = String.Format("It is now {0:d} at {0:t}", DateTime.Now);
            Console.WriteLine(s);
            // Output similar to: 'It is now 4/10/2015 at 10:04 AM'
            
            Decimal pricePerOunce = 17.36m;
            String s1 = String.Format("The current price is {0:C2} per ounce.",pricePerOunce);
            Console.WriteLine(s1);
            // Result if current culture is en-US:
            // The current price is $17.36 per ounce.
            /*
            The following example defines a 6 - character field to hold the string "Year" and some year strings, as well as an 15 - character field to hold the string "Population" and some population data. Note that the characters are right-aligned in the field.
            */
            int[] years = { 2013, 2014, 2015 };
            int[] population = { 1025632, 1105967, 1148203 };
            var sb = new System.Text.StringBuilder();
            sb.Append(String.Format("{0,6} {1,15}\n\n", "Year", "Population"));
            for (int index = 0; index < years.Length; index++)
                sb.Append(String.Format("{0,6} {1,15:N0}\n", years[index], population[index]));
                Console.WriteLine(sb);

            Console.ReadKey();
        }
    }
}

OUTPUT
It is now 2021-05-03 at 7:04 PM
The current price is $17.36 per ounce.
  Year      Population

  2013       1,025,632
  2014       1,105,967
  2015       1,148,203


No comments:

Post a Comment

Hot Topics