convert string to a float value if possible. - CSharp System

CSharp examples for System:String Convert

Description

convert string to a float value if possible.

Demo Code


using System.Xml;
using System.Web;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//  w  w  w .ja  va2s .  com

public class Main{
        /// <summary>
        /// convert string to a float value if possible.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <param name="theDefault">the replace value if string could not convert to float</param>
        /// <returns>a float value</returns>
        public static float ToFloat(this string theSource, float theDefault)
        {
            float tempValue;
            return float.TryParse(theSource.TrimNull("0"), out tempValue) ? tempValue : theDefault;
        }
        /// <summary>
        /// convert string to a float value if possible, if failed, return 0 as default value.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <returns>a float value</returns>
        public static float ToFloat(this string theSource)
        {
            return theSource.ToFloat(0);
        }
        /// <summary>
        /// Check if the string is null or empty, if yes, return the replace string instead.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <param name="replacer">the replace function</param>
        /// <returns>a string</returns>
        public static string TrimNull(this string theSource, Func<string> replacer)
        {
            return string.IsNullOrEmpty(theSource) ? replacer() : theSource;
        }
        /// <summary>
        /// Check if the string is null or empty, if yes, return the replace string instead.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <param name="theReplace">the replace string</param>
        /// <returns>a string</returns>
        public static string TrimNull(this string theSource, string theReplace)
        {
            return string.IsNullOrEmpty(theSource) ? theReplace : theSource;
        }
        /// <summary>
        /// Check if the string is null, if yes, return an empty string instead.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <returns>a string</returns>
        public static string TrimNull(this string theSource)
        {
            return theSource ?? string.Empty;
        }
}

Related Tutorials