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

CSharp examples for System:String Convert

Description

convert string to a double 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;//from w ww  .  j  a  va  2s.  c  o m

public class Main{
        /// <summary>
        /// convert string to a double value if possible.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <param name="theDefault">the replace value if string could not convert to double</param>
        /// <returns>a double value</returns>
        public static double ToDouble(this string theSource, double theDefault)
        {
            double tempValue;
            return double.TryParse(theSource.TrimNull("0"), out tempValue) ? tempValue : theDefault;
        }
        /// <summary>
        /// convert string to a double value if possible, if failed, return 0d as default value.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <returns>a double value</returns>
        public static double ToDouble(this string theSource)
        {
            return theSource.ToDouble(0d);
        }
        /// <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