views:

126

answers:

2

i have an Person object with an age property (int)

i am parsing a file and this value is coming in this format "6.00000000000000"

what is the best way to convert this string into an int in C#

Convert.ToInt32() or Int.Parse() gives me an exception:

Input string was not in a correct format.

+9  A: 

It depends on how confident you are that the input-data will always adhere to this format. Here are some alternatives:

string text = "6.00000000"

// rounding will occur if there are digits after the decimal point
int age = (int) decimal.Parse(text); 

// will throw an OverflowException if there are digits after the decimal point  
int age = int.Parse(text, NumberStyles.AllowDecimalPoint);

// can deal with an incorrect format
int age;
if(int.TryParse(text, NumberStyles.AllowDecimalPoint, null, out age))
{             
   // success
}
else
{
   // failure
} 

EDIT: Changed double to decimal after comment.

Ani
I'd rather use `decimal` than `double` for the first case. Integers should be fine, but in general parsing decimal input to binary floating point is not a good idea. Anyway, your second option is by far the most sensible, +1. If you don't want to deal with exceptions, just use TryParse instead of Parse.
Joren
@Joren:+1. Good point about `decimal`.
Ani
A: 
int age = (int) double.Parse(str);
int age = (int) decimal.Parse(str);
SaeedAlg