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

CSharp examples for System:String Convert

Description

convert string to a decimal 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 ww.j  a va 2 s  .  c  om*/

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