Link to home
Start Free TrialLog in
Avatar of jackjohnson44
jackjohnson44

asked on

c# string to decimal and allow for E notation

Hi,
I have the function below which works for numbers like 1.2 and .03, but not 1.2E26 or 1.2E-26.  Can someone please show me how to alter it?

        public static decimal GetDecimal(string value)
        {
            var retValue = new decimal();
            if (Decimal.TryParse(value, out retValue))
            {
                return retValue;
            }
            else
            {
                throw (new Exception(String.Format("GetDecimal {0}", value)));
            }
        }
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
don't use decimal..
using System;

namespace Numbers
{
    class Program
    {
     static void Main() {
    //
    // Usage of double.Parse on various input strings.
    //
    string[] tests = new string[] {
	    "1,000.00",  // <-- This is 1000
	    "1.000",     // <-- This is 1
	    "0.201",     //
	    "00.001",    // <-- This is 0.001
	    "-0.01",     // <-- This is -0.01
	    "500000000", // <-- Five-hundred million
	    "0.0", // <-- 0
        "1E10" // <-- 10,000,000,000 10 Billion
	    };

    foreach (string test in tests)
        {
        double value = double.Parse(test);
        Console.WriteLine(value);
        }
        //
        // Usage of double.TryParse on various unusual inputs
        //
        string[] unusuals = new string[] 	{
	        "NaN",              // <-- This can be parsed.
	        "MaxValue",         // <-- This fails.
	        "NegativeInfinity",
	        "Programmer",
	        "0.01-0.02",
	        "    0"             // <-- This succeeds and is 0.
	        };
        Console.WriteLine("\nTest for Unusuals\n");
        foreach (string unusual in unusuals) {
            double value;
            if (double.TryParse(unusual, out value)) // Returns bool
                {
                Console.WriteLine("Valid: {0}", value,"\n");
                }
        }
        Console.WriteLine("Press Enter to Continue");
        Console.ReadLine();
        }
    }
}

Open in new window

http://www.dotnetperls.com/double