String Format for Double and Int in C#


String Format for Double [C#]

  

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.
Digits after decimal point
This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.
[C#]
// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"
 
Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.
[C#]
// max. two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"
 
Digits before decimal point
If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.
[C#]
// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567);      // "123.5"
String.Format("{0:00.0}", 23.4567);       // "23.5"
String.Format("{0:00.0}", 3.4567);        // "03.5"
String.Format("{0:00.0}", -3.4567);       // "-03.5"
 
Thousands separator
To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.
[C#]
String.Format("{0:0,0.0}", 12345.67);     // "12,345.7"
String.Format("{0:0,0}", 12345.67);       // "12,346"
 
Zero
Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).
Following code shows how can be formatted a zero (of double type).
[C#]
String.Format("{0:0.0}", 0.0);            // "0.0"
String.Format("{0:0.#}", 0.0);            // "0"
String.Format("{0:#.0}", 0.0);            // ".0"
String.Format("{0:#.#}", 0.0);            // ""
 
Align numbers with spaces
To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.
[C#]
String.Format("{0,10:0.0}", 123.4567);    // "     123.5"
String.Format("{0,-10:0.0}", 123.4567);   // "123.5     "
String.Format("{0,10:0.0}", -123.4567);   // "    -123.5"
String.Format("{0,-10:0.0}", -123.4567);  // "-123.5    "
 
Custom formatting for negative numbers and zero
If you need to use custom format for negative float numbers or zero, use semicolon separator;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.
[C#]
String.Format("{0:0.00;minus 0.00;zero}", 123.4567);   // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567);  // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0);        // "zero"
 
Some funny examples
As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.
[C#]
String.Format("{0:my number is 0.0}", 12.3);   // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3);          // "12aaa.bbb3"
 
 

String Format for Int [C#]

 

Integer numbers can be formatted in .NET in many ways. You can use static method String.Format or instance method int.ToString. Following examples shows how to align numbers (with spaces or zeroes), how to format negative numbers or how to do custom formatting like phone numbers.
Add zeroes before number
To add zeroes before a number, use colon separator „:“
[C#]
String.Format("{0:00000}", 15);          // "00015"
String.Format("{0:00000}", -15);         // "-00015"
 
Align number to the right or left
To align number to the right, use comma „,“ followed by a number of characters. This alignment option must be before the colon separator.
[C#]
String.Format("{0,5}", 15);              // "   15"
String.Format("{0,-5}", 15);             // "15   "
String.Format("{0,5:000}", 15);          // "  015"
String.Format("{0,-5:000}", 15);         // "015  "
 
Different formatting for negative numbers and zero
You can have special format for negative numbers and zero. Use semicolon separator „;“ to separate formatting to two or three sections. The second section is format for negative numbers, the third section is for zero.
[C#]
String.Format("{0:#;minus #}", 15);      // "15"
String.Format("{0:#;minus #}", -15);     // "minus 15"
String.Format("{0:#;minus #;zero}", 0);  // "zero"
 
Custom number formatting (e.g. phone number)
Numbers can be formatted also to any custom format, e.g. like phone numbers or serial numbers.
[C#]
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551);       // "89-5871-2551"
 
 
 

0 comments:

Basic XML Operations in C#

Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications , all gratis open standards.

Here I am explaining you the basic XML operations which is normally used in the  C# coding .


Select XML Nodes by Name [C#]

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.
Suppose we have this XML file.
<Names>

    <Name>

        <FirstName>Vishal</FirstName>

        <LastName>Soni</LastName>

    </Name>

    <Name>

        <FirstName>Bharat</FirstName>

        <LastName> Shekhar</LastName>

    </Name>

</Names>
To get all <Name> nodes use XPath expression /Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.

@[C#]
XmlDocument xml = new XmlDocument();

xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"



XmlNodeList xnList = xml.SelectNodes("/Names/Name");

foreach (XmlNode xn in xnList)

{

  string firstName = xn["FirstName"].InnerText;

  string lastName = xn["LastName"].InnerText;

  Console.WriteLine("Name: {0} {1}", firstName, lastName);

}


The output is:
Name: Vishal Soni
Name: Bharat Shekhar

Select XML Nodes by Attribute Value [C#]

This example shows how to select nodes from XML document by attribute value. Use method XmlNode.Selec­tNodes to get list of nodes selected by the XPath expression. Suppose we have this XML file.
[XML]

<Names>

    <Name type="M"> Bharat</Name>

    <Name type="F"> Shekhar</Name>

    <Name type="M"> Vashistha</Name>

</Names>

To get all name nodes use XPath expression /Names/Name. To get only male names (to select all nodes with specific XML attribute) use XPath expression /Names/Name[@type='M'].
@[C#]
XmlDocument xml = new XmlDocument();

xml.LoadXml(str);  // suppose that str string contains "<Names>...</Names>"



XmlNodeList xnList = xml.SelectNodes("/Names/Name[@type='M']");

foreach (XmlNode xn in xnList)

{

  Console.WriteLine(xn.InnerText);

}


The output is:
Bharat
Vashistha

Select Top XML Nodes using XPath [C#]

This example shows how to select Top N nodes of the specific name from an XML document. To select nodes from XML use method XmlNode.Selec­tNodes. Pass XPath expression as a parameter and the method returns a list of selected nodes. Suppose we have this XML file.
[XML]
<Names>

    <Name>Vishal</Name>

    <Name>Piyush</Name>

    <Name>Shiv</Name>

    <Name>Amit</Name>

    <Name>Bharat</Name>

    <Name>Shekhar</Name>

    <Name>Vashistha</Name>

</Names>
To get all <Name> nodes use XPath expression /Names/Name. If you don't want to selected all nodes, but only top 5 nodes, you can uses XPath expression like this /Names/Name[position() <= 5]. See the example below.
[C#]
XmlDocument xml = new XmlDocument();

xml.LoadXml(str);  // suppose that str string contains "<Names>...</Names>"



XmlNodeList xnList = xml.SelectNodes("/Names/Name[position() <= 5]");

foreach (XmlNode xn in xnList)

{

  Console.WriteLine(xn.InnerText);

}


The output is:
Vishal
Piyush
Shiv
Amit
Bharat

 Hope this will help you ..

Regards ,
Rajesh







1 comments:

Difference between dot net 3.5 and 4.0



S.No
ASP.NET 3.5
ASP.NET 4.0
1
Whether Client data can be directly accessed ?
In ASP.NET 3.5, the data from the client side cannot be directly accessed. The client side data can only be accessed using script manager’s Page methods,
interface named ICallbackEventHandler
or by using the component
XMLHttpHandler.
Whether Client data can be directly accessed ?
In ASP.NET 4, the data from the client side can be
directly accessed using client data view and client
 data context 
 objects.

Following methods are available in ASP.NET 4.0 to access 
Client data directly,
1) Client data controls
2) Client templates
3) Client data context
2
Whether we can set MetaTags (Keywords,Description) in the Page Directive?
In ASP.NET 3.5, two meta tags can be used, one with name as keywords and other with name as description to record the keywords and description for SEO purpose.

Please look atMetaTags for ASP.NET 3.5
Whether we can set MetaTags (Keywords,Description) 
in the Page Directive?
The meta keywords and meta
description is really useful for SEO
optimization of the web page. In
ASP.NET 4, the keywords and
description can be included as part of page directive itself.

Please look at MetaTags for ASP.NET 4.0
3
Whether ViewState can be applied at the Control level ?
ASP.NET 3.5 EnableViewState property cannot be used to apply ViewState at the Control level.It is mainly used at the page level.Its default value is True and its acceptable values ae True and False.
Whether ViewState can be applied at the Control
 level ?
In ASP.NET 4, ViewState mechanism is improved

 to set ViewState at the Contol level besides at 
the page level set by EnableViewState property in 
ASP.NET 3.5 .Its default value is Inherit and
 acceptable values areEnabled,Disabled and Inherit.
4
How ASP.NET 3.5 identifies ClientID ?
In ASP.NET 3.5, ClientId property has to be used to find the dynamically generated client id.
How ASP.NET 4.0 identifies ClientID ?
In ASP.NET 4, a property called
ClientIDMode is newly introduced to 
 identify and record the ClientId easily.

ClientIDMode has following values.
AutoID – Same as ASP.NET 3.5
Static – There won’t be any separate 

clientid generated at run time
Predictable-These are used particularly

 in datacontrols. Format is like clientIDrowsuffix 
with the clientid vlaue
Inherit- This value specifies that a control’s ID

 generation is the same as its parent.


The default value of ClientIDMode for a page

 isPredictable. The default value of ClientIDMode
 for a control is Inherit. Because the default for
 controls isInherit, the default generation mode is
 Predictable.
5
Whether permanent redirection is possible or not ?
There is no RedirectPermanent() method available in ASP.NET 3.5.
Redirect method is less useful than the RedirectPermanent method. It will cause search engine results to be less current, and this can also impact performance because visitors will not be accessing the best URL. Redirect may be most useful for login pages or more complex situations.
Whether permanent redirection is possible or not ?
ASP.Net 4.0 introduced a new URL redirection method RedirectPermanent() which avoids round trips.

We can implement this as shown below:
RedirectPermanent("/newpath/newpage.aspx");
RedirectPermanent returns a 301 HTTP response
—it redirects permanently to another location. 
Search engines such as Google and Bing will
 change their indexes to point to the new page 
directly. To call RedirectPermanent you will need
 to get the Response object from the HttpContext.
Then, you can call RedirectPermanent: if you pass false as the second parameter, you can perform further ac
tions and avoid an exception.
6
Output Caching Enhancement:
OutPut Cache in ASP.Net 3.5 has a limitation - generated content always has to be stored in memory, and on servers that are experiencing heavy traffic, the memory consumed by output caching can compete with memory demands from other portions of a Web application.
Output Caching Enhancement:
ASP.NET 4 adds an extensibility point to output
 caching that enables you to configure one or 
more custom output-cache providers. Output-cache
 providers can use any storage mechanism to 
persist HTML content. This makes it possible to 
create custom output-cache providers for diverse 
persistence mechanisms, which can include local 
or remote disks, cloud storage, and distributed 
cache engines.

In order to know how to implement Custom 
 Output Caching, please refer to the following 
URL,

7
QueryExtender Control for filtering the data returned by EntityDataSource and LinqDataSource controls:
There is no QueryExtender control available in ASP.NET 3.5 to filter the data returned by DataSource Controls( EntityDataSource and LinqDataSource).It has to explicitly use 'Where clause' in the data source.
QueryExtender Control for filtering the data returned 
by EntityDataSource and LinqDataSource controls:
QueryExtender Control is an add-on to the DataSource
 Controls: EntityDataSource and LinqDataSource. 
QueryExtender is used to filter the data returned by 
these controls. As the QueryExtender control relies on 
LINQ, the filter is applied on the database server before the data is sent to the page, which results in very efficient operations.

i.e., QueryExtender Control is intended to be used 
to create filters for data that is retrieved from a data 
 source, without using an explicit Where clause in the
 data source. The control can be used to filter data in
 the markup of a Web page by using declarative syntax.

Please look at QueryExtender Control in ASP.NET 4.0

0 comments: