Reputation:
I am trying to convert string
to integer
from a object's property, where i am facing lot of problems.
1st Method
public class test
{
public string Class { get; set; }
}
//test.Class value is 150.0
var i = Convert.ToInt32(test.Class);
It is saying error that Input String is not in a correct format
2nd Method
int i = 0;
Int32.TryParse(test.Class, out i);
The value of the above code is always zero
3rd Method
int j = 0;
Int32.TryParse(test.Class, NumberStyles.Number, null, out j);
Here i am getting the value as 150
correctly but as I am using null
for IFormatProvider
Will there be any problem with this?
Which is the proper method for converting string to integer with these cases?
Upvotes: 2
Views: 875
Reputation: 186688
The value 150.0 includes decimal separator "." and so can't be converted directly into any integer type (e.g. Int32). You can obtain the desired value in two stage conversion: first to double, then to Int32
Double d;
if (Double.TryParse(test.Class, NumberStyles.Any, CultureInfo.InvariantCulture, out d)) {
Int32 i = (Int32) d;
// <- Do something with i
}
else {
// <- test.Class is of incorrect format
}
Upvotes: 1
Reputation: 2232
As others have said, you can't convert a 150.0 to an integer, but you can convert it to a Double/Single and then cast it to int.
int num = (int)Convert.ToSingle(test.Class) //explicit conversion, loss of information
Source: http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx
Upvotes: 0
Reputation: 1
From the MSDN documentation: you get a FormatException if "value does not consist of an optional sign followed by a sequence of digits (0 through 9)". Lose the decimal point, or convert to a float and then convert to int.
Upvotes: 0
Reputation: 4963
If you sure that test.class
contains float value than better use this
float val= Convert.ToSingle(test.class, CultureInfo.InvariantCulture);
Convert.ToInt32("150.0") Fails Because It is simply not an integer as the error says quite handsomly
Upvotes: 1