-->

22 December 2019

Asp.Net C# String Formatting

  Asp.Net CS By Example       22 December 2019

  String Or Output Formatting:
   we can format the output displayed by the System.Console.Write() , System.Console.WriteLine(),string.format and eval methods.
This enables we to specify the format for integers, floating-point numbers, and even display numbers as currency values.

C# allows we to customize output:
    we can display the myInt value using a total width of 6 using the following statement:
System.Console.WriteLine("myInt = {0, 6}", myInt);


    When the variable is displayed, its value will be padded to this width, so
12345 will padded by one space in front to bring the total width up to 6 characters.
Therefore, this statement displays the following:
myInt = 12345
There is an extra space in front of the value.

    if we use total width value is negative then the extra space add in back of 12345.
System.Console.WriteLine("myInt = {0, -6}.", myInt);

Therefore, this statement displays the following:
myInt =12345 .


The following example displays the value for myDouble with a width of 10, and it rounds the value to three decimal places:
System.Console.WriteLine("myDouble = {0, 10:f2}", myDouble);

Notice the use of f2 in this example; this means that the value is treated as a floating-point number,
as indicated by the format character f, and that the value is to be rounded to two decimal places, as indicated by the 2 after the f.

float myFloat = 1234.56789f;
System.Console.WriteLine("myFloat = {0, 10:f2}", myFloat);
decimal myDecimal = 1234.56789m;
System.Console.WriteLine("myDecimal = {0, 10:f2}", myDecimal);
These examples display the following: myFloat = 1234.56 myDecimal = 1234.56


There are a total of eight format characters we can use to format a number, as shown in below Table.
Format Characters
Format Character Description
f or F Formats a floating-point number
e or E Formats a number using exponential notation
p or P Formats a percentage
n or N Formats a number using comma separators
c or C Formats a local currency number
d or D Formats a decimal number
g or G Formats a number using either the floating-point or exponential notation
x or X Converts an integer to a hexadecimal number


Demo Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringFormatting
{
 public static void Main()
 {
  // formatting integers
  int myInt = 12345;
  int myInt2 = 67890;
  System.Console.WriteLine("myInt = {0, 6}, myInt2 = {1, 5}",myInt, myInt2);
  System.Console.WriteLine("myInt using 10:d = {0, 10:d}", myInt);
  System.Console.WriteLine("myInt using 10:x = {0, 10:x2}", myInt);
  // formatting floating-point numbers
  double myDouble = 1234.56789;
  System.Console.WriteLine("myDouble using 10:f3 = {0, 10:f3}",
  myDouble);
  float myFloat = 1234.56789f;
  System.Console.WriteLine("myFloat using 10:f3 = {0, 10:f3}",
  myFloat);
  decimal myDecimal = 1234.56789m;
  System.Console.WriteLine("myDecimal using 10:f3 = {0, 10:f3}",myDecimal);
  System.Console.WriteLine("myFloat using 10:e3 = {0, 10:e3}",myFloat);
  System.Console.WriteLine("myFloat using 10:p2 = {0, 10:p2}",myFloat);
  System.Console.WriteLine("myFloat using 10:n2 = {0, 10:n2}",myFloat);
  System.Console.WriteLine("myFloat using 10:g2 = {0, 10:g2}",myFloat);
  // formatting currency values
  decimal myMoney = 15123.45m;
  System.Console.WriteLine("myMoney using 10:c2 = {0, 10:c2}",myMoney);
 }
}
        

OutPut:

The output from this program is as follows:
myInt = 12345, myInt2 = 67890
myInt using 10:d = 12345
myInt using 10:x = 3039
myDouble using 10:f3 = 1234.568
myFloat using 10:f3 = 1234.568
myDecimal using 10:f3 = 1234.568
myFloat using 10:e3 = 1.235e+003
myFloat using 10:p2 = 123,456.79 %
myFloat using 10:n2 = 1,234.57
myFloat using 10:g2 = 1.2e+03
myMoney using 10:c2 = $15,123.45
            
C# String Format Method In c#, the string format method is used to format the value of variable or an expression or object and assign to another string variable.
By using string Format method, we can replace the format items in the specified string with the string representation of specified objects.

C# String Format Method Representation Diagram

If we observe above diagram, we inserted a format items inside of string and replacing those formatted items with the specified
string values using Format method.
C# String Format Method Syntax
Following is the syntaxes of defining a string Format method to replace inserted format items within the string
using specified string objects in c# programming language.

public string Format(string, object)
public string Format(string, object, object)
public string Format(IFormatProvider, string, object)

If we observe above syntaxes,
first syntax is used to replaces one or more format items in a string with the string representation of a specified object.
The second syntax is used to replaces the format items in a string with the string representation of two specified objects
and
The third syntax is used to replaces the format items in a specified string with the string representation of corresponding object.

C# String Format Method Example
Following is the example of using string Format() method to assign an object or variable or expression value into
another string in c# programming language.

Demo Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringFormatting
{
    class Class2
    {
        static void Main(string[] args)
        {
            string s = "Name:{0} {1}, Job:{2}, Salary:{3:00,000}";
            string msg = string.Format(s, "Mahesh", "Koli", "Software Developer", 29000f);
            Console.WriteLine("Format Result: {0}", msg);
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

output:

Format Result: Name:Mahesh Koli, Job:Software Developer, Salary:29,000
Press Enter Key to Exit..

If we observe above example, we used a string Format() method to replace a format items in given string.

When we execute above c# program, we will get the result like as shown below.

C# String Format Method Example Result

If we observe above result, the string Format() method has replaced a format items {0} with "Mahesh", {1} with "Koli",
{2} with "Software Developer" and {3} with "29,000." in given string based on our requirements.

C# Format String Items
In above example, we used a string Format() method to replace format items within the string but by using Format() method
we can control appearance of format items.

Following is the example of controlling the appearance of format items using string Format() method in c# programming language.

Demo Code:

using System;
 
namespace StringFormatting
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal num = 75.73789621m;
            DateTime datetime = DateTime.Now;
            Console.WriteLine("Format Decimal: {0:n2}", num);
            Console.WriteLine("DateTime: {0}", datetime);
            Console.WriteLine("Only Date: {0:D}", datetime);
            Console.WriteLine("Only Time: {0:T}", datetime);
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}
            
outputs:
Format Decimal: 12,345.68
DateTime: 27-10-2019 20:01:31
Only Date: 27 October 2019
Only Time: 20:01:31

Press Enter Key to Exit..
            

If we observe above code, we are formatting given decimal number to only decimal value using {0:n2} and formatting datetime value to display
only date {0:d} or time {0:t} based on our requirements.

When we execute above c# program, we will get the result like as shown below.

C# Format String Items using Format Method Example Result

If we observe above result, we are formatting the given item values using Format() method based on our requirements.

In c#, we have a different formats to format the object values using Format() method. Following tables lists the different type of
formats available in c# programming language.


C# Date Time Formats
Following table lists the different type of date time formats available in c# to format the given datetime values.
Generally the Date/Time formats are depend on the user locale so the output may be different.
C# Date Time Formats
Character Description Usage Example
d Short Date {0:d} 29-05-2018
D Long Date {0:D} 29 May 2018
t Short Time {0:t} 05:29:20
T Long Time {0:T} 05:29:20
f or F Long Date Time {0:f} 29 May 2018 05:30:08
g or G Short Date Time {0:g} 29-05-2018 05:31:42
M Short Date {0:M} May 29
r RFC1123 Date Time String {0:r} Tue, 29 May 2018 05:33:02 GMT
s Sortable Date/Time {0:s} 2018-05-29T05:34:10
u Universal Sortable Date {0:u} 2018-05-29 05:35:47Z
U Universal full date {0:U} 29 May 2018 00:08:07
Y Year month pattern {0:Y} May, 2018


C# Number Formats
Following table lists the different type of number formats available in c# to format the given number values.
For example, we are passing decimal value as 12345.67890.
Format Characters
Character Description Usage Example
c Currency {0:c} Rs. 12,345.68
e Scientific {0:e} 1.234568e+004
f Fixed Point {0:f} 12345.68
g General {0:g} 12345.67890
n Thousand Separator {0:n} 12,345.68


C# Custom Formats:
In c#, we can also use custom formats to format the string. Following table lists the different
type of custom formats which we can use to format the strings. For example, we are passing decimal value as 12345.67890.
Format Characters
Character Description Usage Example
0 Zero Placeholder {0:00.00} 12345.67
# Digit Placeholder {0:(#).##} (12345).67
. Decimal Point {0:0.000} 12345.67
, Thousand Separator {0:0,0} 12,345
% Percent {0:0%} 12345%
This is how we can use string Format() method to insert format items into given string and replace those items with their respective values in c# programming language.
logoblog

Thanks for reading Asp.Net C# String Formatting

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.