Output formatting in C#

· 1 min read

See the following examples for the formatting on float and date:

using System;
using System.Globalization;
using System.Threading;

namespace CSharpLearning {
    class Program {
        static void Main(string[] args) {
            
            double f = 0.049;
            
            // print out float: 0.049
            Console.WriteLine(f);

            // keep 2 decimals with rounding
            Console.WriteLine(String.Format("{0:0.00}", f)); // 0.05
            Console.WriteLine("{0:0.00}", f);  // 0.05
            
            // in percentage format
            Console.WriteLine(f.ToString("P")); // 4.900%


            // print out currency/money
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
            int money = 1398737;
            Console.WriteLine(money.ToString("C2")); // $1,398,737.00
            
            
            // print out date
            DateTime d = new DateTime(2020, 2, 8, 12, 7, 7, 123);
            // print out year: 20 20 2020 2020
            Console.WriteLine(String.Format("{0:y yy yyy yyyy}", d));
            // print out month: 2 02 Feb February
            Console.WriteLine(String.Format("{0:M MM MMM MMMM}", d));
            // print out day: 8 08 Sat Saturday
            Console.WriteLine(String.Format("{0:d dd ddd dddd}", d));
            // print out year-month-day: 2020-02-08 Saturday
			Console.WriteLine($"{d:yyyy-MM-dd dddd}");
        }
    }
}