Reading through the MS documentation and samples...
Convert Class (System) | Microsoft Docs[
^]
FormatException
This occurs when the attempt to convert a string value to any other base type fails because the string is not in the proper format. The exception is thrown for the following conversions:
1. A string to be converted to a Boolean value does not equal Boolean.TrueString or Boolean.FalseString.
2. A string to be converted to a Char value consists of multiple characters.
3. A string to be converted to any numeric type is not recognized as a valid number
And if we look at the code block up the page, for the attempt to convert to Int
int newInteger = 0;
try {
System.Console.WriteLine("Enter an integer:");
newInteger = System.Convert.ToInt32(System.Console.ReadLine());
}
catch (System.FormatException) {
System.Console.WriteLine(
"String does not consist of an optional sign followed by a series of digits."
);
}
"String does not consist of an optional sign followed by a series of digits."
It would appear that the only thing that may start a number is either a sign (for positive or negative) or a number.
The values you were provided in your question began with a decimal point, which may be why you are failing.
According to a couple of resources, the correct notation for a decimal value less than 1 is to begin with a "0" before the decimal point. I never really thought about it.
Numbers - Decimal Numbers - In Depth[
^]
Writing a Decimal Number Less Than 1 Given its Name - Tutorialspoint[
^]
Now that we know all of this... what should I do?
As the other answer states, you may want to try using the
TryParse
method
decimal d = 0;
if (!Decimal.TryParse(dataGridView1.Rows[i].Cells[31].Value, out d) {
}
Decimal.TryParse Method (System) | Microsoft Docs[
^]
Another option would be to check the string first to see if the first character is a decimal point; and if so, prepend it with a "0"
string Cell31 = dataGridView1.Rows[i].Cells[31].Value;
if (Cell31.Substring(0,1) == ".") { Cell31 = "0" + Cell31; }
decimal d = Convert.ToDecimal(Cell31);