Parsing/Converting String as Decimal using C#

Parsing/Converting String as Decimal using C#

In this blog, we are going to parse the string to specific Decimal data Type.

Usage:

decimal a2 = TryParsedecimal("234.53453424233432423432", decimal.MinValue);//TRUE

decimal b2 = TryParsedecimal("24.54dasdsa", decimal.MinValue);//FALSE

Response.Write(string.Format("A:{0},B:{1}", a2, b2) + "<br/>");


OUTPUT:

A:234.53453424233432423432,B:-79228162514264337593543950335

Method1: decimal.TryParse

Best to use if there is uncertain about the input string.

              /// <summary>

        /// Parses the string as Decimal.

        /// It wont throw error. Instead it gives the ifFail value if error occurs

        /// </summary>

        public decimal TryParsedecimal(string input, decimal ifFail)

        {

            decimal output;

 

            if (decimal.TryParse(input, out output))

            {

                output = output;

            }

            else

            {

                output = ifFail;

            }

 

            return output;

        }

 

Method 2: decimal.Parse

If you sure about the input string going to be valid, then go for this method.

/// <summary>

        /// Parses the string as Decimal. But if Decimal string is invalid, then it throws error

        /// </summary>

        public decimal Parsedecimal(string input)

        {

            return decimal.Parse(input);

        }

Thanks for reading this article. Have a nice day.

Ebook Download
View all
Learn
View all