Parsing a decimal number from a DataReader

I found a workaround for this error, but now I am very curious why this is happening, I was wondering if anyone else has this error.

My function is this:

public void Blog_GetRating(int blogID, ref decimal rating, ref int voteCount)
{
    // Sql statements
    // Sql commands

    if (DataReader.Read())
    {
        // this line throws a 'Input string was not in a correct format.' error.
        rating = decimal.Parse(DataReader["Rating"].ToString());

        // this works absolutly fine?!
        decimal _rating = 0;
        decimal.TryParse(DataReader["Rating"].ToString(), out _rating);

        rating = _rating;
    }
}

Has anyone ever seen this before?

What's even weirder if I type this:

rating = decimal.Parse("4.0");

which works fine, 4.0 is what comes out of my DataReader.

As I said before, the TryParse method works great, so it doesn’t stop me from porting, but now I’m really interested to know if anyone has an answer.

Looking forward to some answers!

Sean

EDIT - SOLVED

decimal.Parse , , ( ), , null. COALESCE SQL . , , , tryparse , 0 .

+5
5

.

Decimal.Parse() . Decimal.TryParse() , false. - , Decimal.TryParse(). , Decimal.TryParse() false , Decimal.Parse() true . Decimal.TryParse() false, "0".

. Decimal.Parse() , , ( ) , , . , , "4.0" , , .

, . . ?

+10

:

    // this works absolutly fine?!
    decimal _rating = 0;
    decimal.TryParse(DataReader["Rating"].ToString(), out _rating);

TryParse. , TryParse ( false), decimal.Parse decimal.TryParse "" , , .

, , . , , , TryParse .

+2

sql , , tryparse false. - :

 if (Convert.IsDBNull(reader["DecimalColumn"]))
     {
        decimalData = 0m;
     }
     else
     {
        decimalData = reader.GetDecimal(reader.GetOrdinal("DecimalColumn"));
     }
+1
source

Today I faced the same problem. Try the following:

rating = decimal.Parse("4,0");

This will give you the same error.


The reason for this is culture. In French culture, 4.0 appears to be 4.0, and therefore it throws an exception.

decimal.TryParse is a culture-invariant method, and therefore it works great.

+1
source

Change your TryParse and try again:

if (!decimal.TryParse(DataReader["Rating"].ToString(), out _rating))
{
  throw new Exception("Input string was not in a correct format");
}

I bet it throws ...

0
source

All Articles