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
  • Ales: Hi, Thanks for the code… I must say I did not experience any errors decrypting any of my messages. I even...
  • JC: Thanks very useful and well explained
  • Thomas: This is a public static class written in the C# language that does not save state. You can call into the...
  • Simon: Thank you very much for this post! It helped me essentially to overcome obstacels to work with mono!
  • Graham: This is a good research for keyboard shortcuts! Some shortcuts are also compatible for Windows OS. I have...