Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

c# - Converting String to Int causes FormatException

I'm currently getting a value of a string and wanted to place it in an INT to start doing calculations.

string values e.g. is p2 = 33.7; Which is actually a temperature reading in Celsius

this is what i used to convert the p2 to INT:

value = Convert.ToInt32(p2);
tavg = val / cnter;
cnter++;

this code is what i use to place the value converted to a datagridview row cell:

 todayRow.Cells[index++].Value = tavg.ToString();
 this.weatherreport_dgv.Rows.Add(todayRow);   

The error message given by the VS2013 is this:

"An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code Additional information: Input string was not in a correct format."

The error is pointing to the conversion of p2 to INT

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

33.7 is a decimal value, Int32 only does integers. Use Convert.ToDouble/double.Parse to get a floating point value:

double value = double.Parse( p2 );

Or if you really do want it as an integer:

int value = (int)double.Parse( p2 );

You'll lose the decimals though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...