How can I convert a string like "09335887170" to an integer? Here is what I have tried:
string a = "09335887170";
int myInt;
bool isValid = int.TryParse(a, out myInt); // it returns false in this case
if (isValid)
{
int plusOne = myInt + 1;
MessageBox.Show(plusOne.ToString());
}
MessageBox.Show(a);
int stringToInt = Convert.ToInt32("09335887170"); // it returns nothing with no error
MessageBox.Show((stringToInt + 1).ToString());
int test = int.Parse(a); //it has type convertion error
MessageBox.Show((test + 1).ToString());
The maximum value of a Int32 (or only int) is 2,147,483,647
you need a UInt64 or Int64 or Long
string a = "09335887170";
Int64 myInt;
bool isValid = Int64.TryParse(a, out myInt);
if (isValid)
{
int plusOne = myInt + 1;
MessageBox.Show(plusOne.ToString());
}
result = Convert.ToInt64(value);
Look here for more info.
(Found online, im not really in c#)
that number exceeds the max int value. use a long instead.
Try this
Int64 no = Convert.ToInt64( "09335887170");
Related
So i have a question. I'm trying do make a function witch returns a number, but the problem is that i can't convert int to string. My functions looks like this:
static string EnemyDmg(EnemyDmg _dmg)
{
string result = "";
int EnemyDmg
= CharAttack - EnemyDefense;
if (EnemyDmg < 1)
EnemyDmg = 4;
result = EnemyDmg;
return result;
}
but it should do this
int EnemyDmg
= CharAttack - EnemyDefense;
if (EnemyDmg < 1)
EnemyDmg = 4;
Console.WriteLine(EnemyName + " takes " + EnemyDmg + " Damage");
has anyone an idea?
PS: The 4 is just a random number.
should be static int EnemyDmg(EnemyDmg _dmg). You should return an int, and convert to string outside the function iif you need that
Anyway, to convert a String s into an int i:
int i = Int32.Parse(s);
to convert an int i into a string s
string s = i.ToString();
string s = ""+i; // more "java-like"
This question is a bit ambiguous; I'm not sure why you've done it this way.
You can convert a C# integer to a string with the .ToString() method, like this:
int a = 12;
string aString = a.ToString();
Console.WriteLine(a);
https://dotnetfiddle.net/sMC3hU
static string toStr(int intInput)
{
string str = intInput.ToString();
return str;
}
}
This code will do it for you. There is no need to use if statement as there is no any specific requirement, it will make more complicated code.
or else
you can direct use ToString parameter if there is an user input just refer to the 3rd line.
I write a method to convert the string into double,here is the code
public double convertToDouble(string number)
{
string temp = number;
if (number.Contains("x"))
{
int locationE = number.IndexOf("x");
string exponent = number.Substring(locationE + 5, number.Length - (locationE + 5));
temp = number.Substring(0, locationE - 1) + "E" + exponent;
}
return Convert.ToDouble(temp);
}
But if the temp variable passed in as null or empty string, the conversion will fail. How could i write this part.
Why do you want to write a new method for this purpose, while you could use the more safest one, double.TryParse.
double number;
// The numberStr is the string you want to parse
if(double.TryParse(numberStr, out number))
{
// The parsing succeeded.
}
If you don't like the above approach and you want to stick with your method, then the only option I see is to throw an exception.
public double convertToDouble(string number)
{
if(string.IsNullOrWhiteSpace(number))
{
throw new ArgumentException("The input cannot be null, empty string or consisted only of of white space characters", "number");
}
string temp = number;
if (number.Contains("x"))
{
int locationE = number.IndexOf("x");
string exponent = number.Substring(locationE + 5, number.Length - (locationE + 5));
temp = number.Substring(0, locationE - 1) + "E" + exponent;
}
return Convert.ToDouble(temp);
}
Depends on what do you want to happen when the number can't be converted.
You could try this:
public double convertToDouble(string number)
{
string temp = number;
if (number.Contains("x"))
{
int locationE = number.IndexOf("x");
string exponent = number.Substring(locationE + 5, number.Length - (locationE + 5));
temp = number.Substring(0, locationE - 1) + "E" + exponent;
}
double returnDouble;
if(double.TryParse(temp, out returnDouble))
return returnDouble;
// Return whatever or throw an exception, etc.
return 0;
}
As a further tip, it looks like you are converting something like [number] x 10^[exponent] to [number]E[exponent], if so, this could be easily converted as:
public double convertToDouble(string number)
{
if(String.IsNullOrWhiteSpace(number))
return 0; // or throw exception, or whatever
// Instead of all those "IndexOf" and "Substrings"
var temp = number.Replace("x 10^", "E");
double returnDouble;
if(double.TryParse(temp, out returnDouble))
return returnDouble;
// Return whatever or throw an exception, etc.
return 0;
}
This could be further prettified without hurting readability, but I'll leave that to you
I am retrieving the OEM number from a Windows mobile smart device, and am trying to figure out how to use a returned value in an if statement.
Below is the code I use to return the value. I would like to make sure the OEM number is always 86.09.0008 and if it is not i would like it to let me know.
class oem
{
const string OEM_VERSION = "OEMVersion";
private const int SPI_GETOEMINFO = 258;
private const int MAX_OEM_NAME_LENGTH = 128;
private const int WCHAR_SIZE = 2;
[DllImport("coreDLL.dll")]
public static extern int SystemParametersInfo(int uiAction, int uiParam, string pBuf, int fWinIni);
[DllImport("CAD.dll")]
public static extern int CAD_GetOemVersionNumber(ref System.UInt16 lpwMajor, ref System.UInt16 lpwMinor);
public string getOEMVersion()
{
System.UInt16 nMajor = 0;
System.UInt16 nMinor = 0;
uint nBuild = 0;
int status = CAD_GetOemVersionNumber(ref nMajor, ref nMinor);
if (((System.Convert.ToBoolean(status))))
{
string sMajor = String.Format("{0:00}", nMajor); //in 2-digits
string sMinor = String.Format("{0:00}", nMinor); //in 2-digits
string sBuild = String.Format("{0:0000}", nBuild); //in 4-digits
return (sMajor + "." + sMinor + "." + sBuild);
}
else // failed
{
return ("00.00.0000");
}
I'm calling this from my main form like so:
label1.Text = oemver.getOEMVersion();
if statements require a bool value. In your case you should compare the value you require with the value you obtained
if(status == 86.09.0009)//...
Note the double '==' which is an operator that checks for equality. Contrast this with the single '=' which performs an assignment.
Also note that int does not allow for decimals. Considering that this number has two decimals I believe you need to get this as a string.
well, just do something like this in you "main" :
string myString = getOEMVersion();
if(myString == "86.09.0009")
{//Whatever you're willing to do
}
If I understood your question, you should do this:
oem someOem = new oem();
if (oem.getOEMVersion() == "86.09.0009") {
// ok
} else {
// fail
}
I am not sure what you mean but if I understand you question you want to use the result of the GetOEMVersion method in an ifstatement.
string OEMVersion = getOEMVersion();
if(OEMVersion == "86.09.0009")
{
// Do something
}
else
{
// fail
}
You are missing :
[DllImport("CAD.dll")]
public static extern int CAD_GetOemBuildNumber(ref uint lpdwBuild);
int build = CAD_GetOemBuildNumber(ref nBuild);
to get the build.
how could I trim and convert a string as following:
string abc = "15k34"
int x = first two characters of abc // should be 15
but if abc begins with "0"
for example - string abc = "05k34"
int x = first two characters of abc // should be 5
Try with following code:
string str = "15k34";
int val;
if (str.Length>1)
{
if (int.TryParse(str.Substring(0, 2), out val))
{
//val contains the integer value
}
}
string abc = "15k34";
int x = 0;
//abc = "05k34";
int val;
if (!string.IsNullOrEmpty(abc) && abc.Length > 1)
{
bool isNum = int.TryParse(str.Substring(0, 2), out val);
if (isNum)
{
x = val;
}
}
I think from the pseudocode you will typically have numbers with 'k' in them representing thousands.
So...
string abc = "15k34";
string[] numbers = abc.Split('k'); //This will return a array { "15", "34" }
int myInt = Convert.ToInt32(numbers[0]);
If the string was "05k34" the value of myInt would be 5 then.
documentation:
http://msdn.microsoft.com/en-us/library/1bwe3zdy
http://msdn.microsoft.com/en-us/library/bb397679.aspx
How do I convert a string to an integer in C#?
If you're sure it'll parse correctly, use
int.Parse(string)
If you're not, use
int i;
bool success = int.TryParse(string, out i);
Caution! In the case below, i will equal 0, not 10 after the TryParse.
int i = 10;
bool failure = int.TryParse("asdf", out i);
This is because TryParse uses an out parameter, not a ref parameter.
int myInt = System.Convert.ToInt32(myString);
As several others have mentioned, you can also use int.Parse() and int.TryParse().
If you're certain that the string will always be an int:
int myInt = int.Parse(myString);
If you'd like to check whether string is really an int first:
int myInt;
bool isValid = int.TryParse(myString, out myInt); // the out keyword allows the method to essentially "return" a second value
if (isValid)
{
int plusOne = myInt + 1;
}
int a = int.Parse(myString);
or better yet, look into int.TryParse(string)
string varString = "15";
int i = int.Parse(varString);
or
int varI;
string varString = "15";
int.TryParse(varString, out varI);
int.TryParse is safer since if you put something else in varString (for example "fsfdsfs") you would get an exception. By using int.TryParse when string can't be converted into int it will return 0.
Do something like:
var result = Int32.Parse(str);
If you are sure that you have "real" number in your string, or you are comfortable of any exception that might arise, use this.
string s="4";
int a=int.Parse(s);
For some more control over the process, use
string s="maybe 4";
int a;
if (int.TryParse(s, out a)) {
// it's int;
}
else {
// it's no int, and there's no exception;
}
4 techniques are benchmarked here.
The fastest way turned out to be the following:
y = 0;
for (int i = 0; i < s.Length; i++)
y = y * 10 + (s[i] - '0');
"s" is your string that you want converted to an int. This code assumes you won't have any exceptions during the conversion. So if you know your string data will always be some sort of int value, the above code is the best way to go for pure speed.
At the end, "y" will have your int value.
int i;
string whatever;
//Best since no exception raised
int.TryParse(whatever, out i);
//Better use try catch on this one
i = Convert.ToInt32(whatever);
bool result = Int32.TryParse(someString, out someNumeric)
This method will try to convert someString into someNumeric, and return a result depending on whether or not the conversion is successful: true if conversion is successful and false if conversion failed. Take note that this method will not throw an exception if the conversion failed like how Int32.Parse method did and instead returns zero for someNumeric.
For more information, you can read here:
https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
&
How to convert string to integer in C#
int i;
string result = Something;
i = Convert.ToInt32(result);
You can use either,
int i = Convert.ToInt32(myString);
or
int i =int.Parse(myString);
class MyMath
{
public dynamic Sum(dynamic x, dynamic y)
{
return (x+y);
}
}
class Demo
{
static void Main(string[] args)
{
MyMath d = new MyMath();
Console.WriteLine(d.Sum(23.2, 32.2));
}
}