什么是将"6.00000000000000"转换为整数属性的最简单方法

leo*_*ora 2 c# parsing integer

我有一个具有age属性的Person对象(int)

我正在解析一个文件,这个值的格式是"6.00000000000000"

在C#中将此字符串转换为int的最佳方法是什么?

Convert.ToInt32() or Int.Parse() gives me an exception:
Run Code Online (Sandbox Code Playgroud)

输入字符串的格式不正确.

Ani*_*Ani 12

这取决于您对输入数据始终遵循此格式的信心.以下是一些替代方案:

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
} 
Run Code Online (Sandbox Code Playgroud)

编辑:更改doubledecimal评论后.