12 Jun

C# String Formatting for Double

This example converts the numeric value of this instance to its equivalent string representation, using the specified format.

C# code examples for double formatting:


        /// 
        /// String formatting for double
        /// 
        public void Test1()
        {
            // just two decimal places
            string format1 = string.Format("{0:0.00}", 123.4567);      
            string format2 = string.Format("{0:0.00}", 123.45);        
            string format3 = string.Format("{0:0.00}", 123.0);         
            // format1 = "123.46"
            // format2 = "123.45"
            // format3 = "123.00"


            // max. two decimal places
            string format4 = string.Format("{0:0.##}", 123.4567);      
            string format5 = string.Format("{0:0.##}", 123.4);         
            string format6 = string.Format("{0:0.##}", 123.0);
            // format4 = "123.46"
            // format5 = "123.4"
            // format6 = "123"

            // at least two digits before decimal point
            string format7 = string.Format("{0:00.0}", 123.4567);      
            string format8 = string.Format("{0:00.0}", 12.3456);       
            string format9 = string.Format("{0:00.0}", 1.2345);        
            string format10 = string.Format("{0:00.0}", -1.2345);
            // format7  = "123.5"
            // format8  = "12.3"
            // format9  = "01.2"
            // format10 = "-01.2"
        }

More information about string formatting:
http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx

Leave a Reply

Your email address will not be published. Required fields are marked *