mfc
mfc

Reputation: 3026

Cast string to decimal? (nullable decimal) by extension method

I want to cast a string to a decimal?. With reference to a previous question here

one of the answers gave a object extension to convert objects like so

public static class ObjectExtensions
{
    public static Nullable<T> ToNullable<T>(this object input)
        where T : struct
    {
        if (input == null)
            return null;
        if (input is Nullable<T> || input is T)
            return (Nullable<T>)input;
        throw new InvalidCastException();
    }
}

usage :

object value = 123.45m;
decimal? dec = value.ToNullable<decimal>();

The above does not work with string however, is it possible to define a companion to the above method to specifically handle strings?

specifically like what I would like to be able to do is :-

object v1 = 123.45m;
decimal? d1 = v1.ToNullable<decimal>();

object v2 = "123.45";
decimal? d2 = v2.ToNullable<decimal>();

Upvotes: 2

Views: 4168

Answers (4)

user2662006
user2662006

Reputation: 2294

Here is what is work for me

1- Create following method inside a class (ex ValidationHelper)

     public static decimal? Todecimal(string s,decimal defValue=0)
    {
        if (s.Trim()!="")
        {
            return Convert.ToDecimal(s);
        }
        else
        {
            return defValue;
        }
    }

and then you can use it anywhere in your app like this

prod.Qty = ValidationHelper.Todecimal(txtQty.Text,1);//ex: assuming the default value for Qty is 1. 

Hope this will help someone. Thanks

Upvotes: 0

AFract
AFract

Reputation: 9723

Given your extension function, why not something like :

public static class ObjectExtensions
    {
        public static Nullable<T> ToNullable<T>(this object input)
            where T : struct
        {
            if (input == null)
                return null;
            if (input is Nullable<T> || input is T)
                return (Nullable<T>)input;
            else if (input is string)
                return (T)Convert.ChangeType(input, typeof(T));

            throw new InvalidCastException();
        }
    }

It will work for numeric types (supported by ChangeType), and even Dates and so.

Of course, "input" must be convertible to desired type (beware of culture-specific constraints).

To improve this, you could pass to "ChangeType" (at third parameter) the Culture you want to work with, for example return ((T)Convert.ChangeType(input, typeof(T), new CultureInfo("en-US")));

You can also add stuff in this method to handle exceptions, etc

Upvotes: 2

Sarrus
Sarrus

Reputation: 631

A simple extension method converts string to decimal. For not null strings of course

public static class StringExtensions
{
   public static decimal? ToNullableDecimal(this string s)
   {
      decimal value;
      if (!Decimal.TryParse(s, out value)
         return null;
      return value;
   }
}

Upvotes: 3

dannydk
dannydk

Reputation: 214

You could do something like this:

string nds = null;
decimal? d = (nds != null) ? Convert.ToDecimal(nds) : default(decimal?);

Upvotes: 2

Related Questions