开发者

How to check for valid value before converting Decimal

开发者 https://www.devze.com 2022-12-10 12:19 出处:网络
I assume th开发者_运维技巧is will blow up if total is null (I don\'t recall if decimals are initalized to null at the beginning or zero)

I assume th开发者_运维技巧is will blow up if total is null (I don't recall if decimals are initalized to null at the beginning or zero)

public int SomePropertyName
{
    get { return Convert.ToInt32(Decimal.Round(total)); }
}

So should I check for null or > 0 ?


Decimal is a value type - there's no such value as "null" for a decimal.

However, it's perfectly possible for a decimal to be out of range for an int. You might want:

decimal rounded = decimal.Round(total);
if (rounded < int.MinValue || rounded > int.MaxValue)
{
    // Do whatever you ought to here (it will depend on your application)
}
return (int) rounded;

I'm somewhat confused as to why you're using Convert.ToInt32 at all though, given that your property is declared to return a decimal. What's the bigger picture here? What are you trying to achieve?


Decimal is a value type and can not be null.

If you need to know if it had been initialized, you should probably use a nullable decimal:

Decimal? total = null;

public int SomePropertyName
{
    get 
    { 
        if (total.HasValue) Convert.ToInt32(Decimal.Round(total.Value)); 
        return 0; // or whatever
    }
}


Decimals are value types, and so cannot be null.

So no need to check there..


As others have said, Decimal is a value type and cannot be null. However, if converting from a string then Decimal.TryParse is your friend...


System.Decimal is a value type, so it cannot be null. Second thing, the method's return value is decimal, so why would you want to convert to a Int32?

0

精彩评论

暂无评论...
验证码 换一张
取 消