2

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?

14
  • 2
    I would guess in your system decimal separator is "," Commented Jun 28, 2013 at 5:44
  • 4
    Are you sure you can convert "150.0" which is a floating point value to an integer? Commented Jun 28, 2013 at 5:45
  • @athabaska, I am not sure about wat u saying? Where to check that? So the answer is? Commented Jun 28, 2013 at 5:47
  • @Patashu, Am not sure. Won't we able to convert it? Commented Jun 28, 2013 at 5:50
  • 1
    A couple of folks here have already suggested that you parse it as a double and then cast to an int. Or, you can Split(".") and throw away the fractional part of the numeric text. I'm a little surprised that the TryParse is actually returning a value. Commented Jun 28, 2013 at 5:57

4 Answers 4

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

it may contain anything like 50, 50.0, 150, 150.0 etc. So i need to convert these value to int but not float
0

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.

Comments

0

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

Comments

Your Answer

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