Check if decimal value is null

140,655

Solution 1

A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue

Solution 2

you can use this code

if (DecimalVariable.Equals(null))  
{
   //something statements
}

Solution 3

decimal is a value type in .NET. And value types can't be null. But if you use nullable type for your decimal, then you can check your decimal is null or not. Like myDecimal?

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.

if (myDecimal.HasValue)

But I think in your database, if this column contains nullable values, then it shouldn't be type of decimal.

Solution 4

Assuming you are reading from a data row, what you want is:

if ( !rdrSelect.IsNull(23) ) 
{ 
   //handle parsing
}

Solution 5

Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).

Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue

Share:
140,655

Related videos on Youtube

Laziale
Author by

Laziale

Updated on July 09, 2022

Comments

  • Laziale
    Laziale almost 2 years

    I would like to check if the decimal number is NULL or it has some value, since the value is assigned from database in class object:

    public decimal myDecimal{ get; set; }
    

    and then I have

    myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
    

    I am trying:

    if (rdrSelect[23] != DBNull.Value)
                        {
                            myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
                        }
    

    But I am getting this:

    the result of the expression is always 'true' since a value of type 'decimal' is never equal to null

    How can I check if that decimal number has some value?

    • Federico Berasategui
      Federico Berasategui over 11 years
      Decimal is a value type. It can never be null. If your column in your db is nullable, then it should be represented by a Decimal? (which is the short hand for System.Nullable<Decimal>
    • Andy Refuerzo
      Andy Refuerzo over 11 years
      Convert.ToDecimal will fail if rdrSelect[23] is null from the database.
    • Servy
      Servy over 11 years
      So did you read the error message. It seems rather clear. decimal can't ever be null, it will always have a value.
  • R.Akhlaghi
    R.Akhlaghi over 5 years
    dear @AshishJain , dear brian your welcome! have happy coding :)
  • Daniel ZA
    Daniel ZA about 5 years
    Perfect solution for a non-nullable type decimal.