Home About

February 3rd, 2009

Converting C# strings to other types - 0

If you are interested in turning a C# string into an integer, float, double or any other kind look no further. In todays post we make use of the convert and parse methods to convert strings into numbers.

In C# the Convert class binds all the basic data types together. It is possible to convert (cast) to and from most data types by using this class. Be careful that you are likely to lose information if you are casting to a type that hold less information.

Example 1: How to convert a C# string to an integer

string myString = “1024″;
int myInteger = Convert.ToInt32(myString);

Example 2: How to convert a C# integer to a string

int myInteger = 1024;
string myString = Convert.ToString(myInteger);

Example 3: How to convert a C# float/double to a string

It is possible to directly convert a float to a string, but not the other way around. Note that floating point type values in C# are automatically a double unless you force the compiler (f) to turn them into a float.

float myFloat = 1000.245f; // We need an “f”
string myString1 = Convert.ToString(myFloat);

double myDouble = 1000.245; // No need for an “f”
string myString2 = Convert.ToString(myDouble);

Example 4: How to convert a C# string to a float/double

If you would like to convert a string to a float you will need to convert it to a double first, and then cast it down. A float contains only 32 bits of information, and is thus less precise than a double (which holds 64 bits).

string myString = “1000.245″;
double myDouble = Convert.ToDouble(myString); // This is not a problem
float myFloat = (float) Convert.ToDouble(myString); // But we need to cast a float

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google
  • Reddit

Tags: , , ,

Leave a Reply


Recent Comments
  • Hakbor: This works fine. But to get the NUnit to use my current tests (and not the old ones) , it is not sufficient...
  • Alberto: Your plugin is very useful; I installed it on several different blogs I manage and I’m very happy with...
  • Nelson: Saved me from doing it myself. Good article.
  • andy: i am currently playing taiwanese server wow in 奈辛瓦里(PVP) and i would like to realm transfer to...
  • berties: any english speaking playing on a taiwanese server?