Parsing/Converting String as Float using C#

Parsing/Converting String as Float using C#

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

Usage:

float a1 = TryParsefloat("234.53453", float.MinValue);//TRUE

float b1 = TryParsefloat("24.54f", float.MinValue);//FALSE

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

OUTPUT:

A:234.5345,B:-3.402823E+38

Method1: float.TryParse

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

     

        /// <summary>

        /// Parses the string as Float.

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

        /// </summary>

        public float TryParsefloat(string input, float ifFail)

        {

            float output;

 

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

            {

                output = output;

            }

            else

            {

                output = ifFail;

            }

 

            return output;

        }

 

Method 2: float.Parse

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

        /// <summary>

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

        /// </summary>

        public float Parsefloat(string input)

        {

            return float.Parse(input);

        }

Thanks for reading this article. Have a nice day.