3

How to convert a string to number in C#? What are the various ways.

1
  • 1
    Welcome to StackOverflow. Please tag your questions correctly. C and C# are very different languages. Commented Jul 4, 2010 at 15:50

7 Answers 7

13

Most of the numerical primitives have Parse and TryParse methods, I'd recommend using these. Parse will throw an exception if the format of the string being parsed is not recognised, whereas TryParse are fault tolerant.

int num = int.Parse("1");

int num = 0;
if (int.TryParse("1", out num)) {
    // do something here.

You can also use Convert.ToInt32 etc....

Sign up to request clarification or add additional context in comments.

Comments

5
static void Main(string[] args)
{
    String textNumber = "1234";
    int i = Int32.Parse(textNumber);
    double d = Double.Parse(textNumber);
    decimal d2 = Decimal.Parse(textNumber);
    float f = float.Parse(textNumber);
}

Values in variables after execution of these commands:

textNumber = "1234"
i = 1234
d = 1234.0
d2 = 1234
f = 1234.0

Comments

4

Here are the various ways, and examples:

http://msdn.microsoft.com/en-us/library/bb397679.aspx

Comments

2

Int32.Parse Double.Parse Decimal.Parse

etc.

Comments

2

int myVar = int.Parse(string);

But with using Parse only you will need to have some form of exception handling if the passed string, isn't a number.

Thats why you should use TryParse

Then you can have

int nr;
if (int.TryParse(mystring, out nr) == false) {
//do something as converting failed
}

Comments

0

in C# you can convert a string to a number by:

Convert.ToUInt32("123");

Convert.ToInt64("678");   // to long

Convert.ToDouble("123");

Convert.ToSingle("146");

you can check this website for full detail : http://msdn.microsoft.com/en-us/library/bb397679.aspx

Comments

0

There is one thing to be aware of, when parsing decimal numbers:

The .NET framework will use the decimal number separators configured in Windows. For example here in Germany we write "1.129.889,12" which is "1,129,889.12" in the USA. Thus double.Parse(str) will behave differently.

You can however specify an IFormatProvider object as second parameter (this also applies to the ToString method). I'll make an example:

var ci = CultureInfo.InvariantCulture;
double a = double.Parse("98,89");
double b = double.Parse("98,89", ci);
Console.WriteLine(a.ToString(ci));
Console.WriteLine(b.ToString(ci));

The output on my computer is:

98.89
9889

So if you are for example reading configuration files, that use a number format independent of the interface language (which makes sense for configuration files), be sure to specify a proper IFormatProvider.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.