Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to int and test success in C#

How can you check whether a string is convertible to an int?

Let's say we have data like "House", "50", "Dog", "45.99", I want to know whether I should just use the string or use the parsed int value instead.

In JavaScript we had this parseInt() function. If the string couldn't be parsed, it would get back NaN.

like image 375
Robin Rodricks Avatar asked Jan 01 '09 22:01

Robin Rodricks


People also ask

Can you convert a string to an int in C?

In C, the atoi() function converts a string to an integer.

Can you convert a string into an int when and how?

In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.

What happens if atoi fails in C?

It is a perfectly good, sound function from the C standard. If you care about success/failure, then you clearly should not use atoi(); there is no way for it to tell you whether it succeeded and returned 0 or failed and returned 0. atoi is not deprecated it was never in the standard to begin with.

Can we use stoi in C?

What Is stoi() in C++? In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings. The stoi() function is relatively new, as it was only added to the language as of its latest revision (C++11) in 2011.


1 Answers

Int32.TryParse(String, Int32) - http://msdn.microsoft.com/en-us/library/f02979c7.aspx

  bool result = Int32.TryParse(value, out number);   if (result)   {      Console.WriteLine("Converted '{0}' to {1}.", value, number);            } 
like image 173
Johnno Nolan Avatar answered Sep 17 '22 10:09

Johnno Nolan