whats the easiest way to convert "6.00000000000000" to an integer property
i have an Person object with an age property (int)
i am parsing a 开发者_Go百科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.
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.
int age = (int) double.Parse(str);
int age = (int) decimal.Parse(str);
精彩评论