1

I need convert String of input of table database to Integer value in C# .NET 4 and tried this code inspired from this Link:

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

But I've this error:

Compiler Error Message: CS0029: Cannot implicitly convert type 'int' to 'string'

EDIT

Solved with:

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

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

In output I've 2,45, many thanks!

Mong Zhu
  • 20,890
  • 7
  • 33
  • 66

4 Answers4

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

should be

string Entry_Level = "2,45";

Why not go for this though:

int i = 2,45;

But since this is not an integer, you'll need one of the built-in decimal types:

/* 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 

See this thread for more information about decimal vs double.

Community
  • 1
  • 1
Moeri
  • 8,814
  • 5
  • 40
  • 53
  • 2
    This is fine, but neglects any consideration of what happens when you pass `"2,45"` to `Convert.ToInt32()` – David Heffernan Apr 14 '14 at 08:52
  • The double vs decimal issue is not one of precision. It's about binary or decimal representation. – David Heffernan Apr 14 '14 at 09:58
  • It's not exactly about precision, but precision does come into play when comparing the two. I've added a link with a full explanation of decimal vs double – Moeri Apr 14 '14 at 11:09
  • I have a solid understanding of the difference between decimal and double, and I am here to tell you that the key issue is decimal vs binary rather than precision. – David Heffernan Apr 14 '14 at 11:11
1

The value 2,45 does not represent an integer. It is a real value. So I believe that you are actually looking for Convert.ToDouble or Convert.ToDecimal. Or perhaps double.Parse or decimal.Parse.

You may also need to consider what happens when you run your code on a machine that does not use , as the decimal separator. Consider using the overloads that accept IFormatProvider.

David Heffernan
  • 572,264
  • 40
  • 974
  • 1,389
0

try this one

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

You can use the line of code below which will remove your compile error but it will through and Runtime Exception cause 2,45 is not a valid integer.

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

I will suggest you to write the below line of codes which will help you to get the value 2.45 on your variable named i

decimal i;
string Entry_Level = "2,45";
Entry_Level = Entry_Level.Replace(',', '.');
i = Convert.ToDecimal(Entry_Level);  
Mong Zhu
  • 20,890
  • 7
  • 33
  • 66