【问题标题】:whats the easiest way to convert "6.00000000000000" to an integer property将“6.00000000000000”转换为整数属性的最简单方法是什么
【发布时间】:2011-04-23 11:12:27
【问题描述】:

我有一个带有年龄属性 (int) 的 Person 对象

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

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

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

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

【问题讨论】:

  • 你搜索过这个吗?这是stackoverflow.com/questions/2344411/…的副本
  • @ChrisF:我不认为这是完全重复的。您链接的问题是将整数字符串转换为int。这个问题是关于将恰好代表整数值的十进制字符串转换为int。差异很小但很相关:这就是为什么这里的答案包括doubledecimal 解析,以及NumberStyles.AllowDecimalPoint 选项。

标签: c# parsing integer


【解决方案1】:
int age = (int) double.Parse(str);
int age = (int) decimal.Parse(str);

【讨论】:

    【解决方案2】:

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

    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
    } 
    

    编辑:评论后将double 更改为decimal

    【讨论】:

    • 对于第一种情况,我宁愿使用decimal 而不是double。整数应该没问题,但通常将十进制输入解析为二进制浮点并不是一个好主意。无论如何,您的第二个选项是迄今为止最明智的,+1。如果您不想处理异常,只需使用 TryParse 而不是 Parse。
    猜你喜欢
    • 2012-02-05
    • 2014-05-09
    • 2010-12-23
    • 1970-01-01
    • 2012-01-07
    • 2020-01-16
    相关资源
    最近更新 更多