You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Output formatting in C#

Ben Liu
Ben Liu

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}");
        }
    }
}

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp