编译器错误消息:CS0029:无法将类型'int'隐式转换为'string'

时间:2014-04-14 08:49:30

标签: c#

我需要将表数据库输入的 String 转换为C#.NET 4中的整数值,并尝试使用此Link启发此代码:

    int i;
    string Entry_Level = Convert.ToInt32("2,45");
    i = Convert.ToInt32(Entry_Level); 

但我发现了这个错误:

  

编译器错误消息:CS0029:无法隐式转换类型' int'到'字符串'

修改

解决:

    decimal i;
    string Entry_Level = "2,45";
    i = Convert.ToDecimal(Entry_Level);

    Response.Write(i.ToString());
    Response.End();

在输出I&#2,4; 2,45,非常感谢!

4 个答案:

答案 0 :(得分:4)

string Entry_Level = Convert.ToInt32("2,45");

应该是

string Entry_Level = "2,45";

为什么不这样做呢:

int i = 2,45;

但由于这不是整数,因此您需要一种内置的十进制类型:

/* use this when precision matters a lot, for example when this is a unit price or a percentage value that will be multiplied with big numbers */
decimal i = 2.45 


/*  use this when precision isn't the most important part. 
It's still really precise, but you can get in trouble when dealing with really small or really big numbers. 
Doubles are fine in most cases.*/
double i = 2.45 

请参阅this thread for more information about decimal vs double

答案 1 :(得分:1)

2,45不代表整数。这是一个真正的价值。所以我相信您实际上在寻找Convert.ToDoubleConvert.ToDecimal。或者也许double.Parsedecimal.Parse

您可能还需要考虑在不使用,作为小数分隔符的计算机上运行代码时会发生什么。考虑使用接受IFormatProvider的重载。

答案 2 :(得分:0)

尝试这个

string Entry_Level = Convert.ToInt32("2,45").toString()

答案 3 :(得分:0)

你可以使用下面的代码行来删除你的编译错误,但它会通过和运行时异常导致2,45不是一个有效的整数。

string Entry_Level = Convert.ToInt32("2,45").ToString(); 

我建议你写下面的代码行,这些代码可以帮助你获得名为i的变量值2.45

decimal i;
string Entry_Level = "2,45";
Entry_Level = Entry_Level.Replace(',', '.');
i = Convert.ToDecimal(Entry_Level);