Best way to display decimal without trailing zeroes

前端 未结 14 1449
终归单人心
终归单人心 2020-11-27 04:49

Is there a display formatter that will output decimals as these string representations in c# without doing any rounding?

// decimal -> string

20 -> 20         


        
14条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 05:03

    I made the below extension methods for myself to fit one of my projects, but maybe they'll be beneficial to someone else.

    using System.Numerics;
    using System.Text.RegularExpressions;
    internal static class ExtensionMethod
    {
        internal static string TrimDecimal(this BigInteger obj) => obj.ToString().TrimDecimal();
        internal static string TrimDecimal(this decimal obj) => new BigInteger(obj).ToString().TrimDecimal();
        internal static string TrimDecimal(this double obj) => new BigInteger(obj).ToString().TrimDecimal();
        internal static string TrimDecimal(this float obj) => new BigInteger(obj).ToString().TrimDecimal();
        internal static string TrimDecimal(this string obj)
        {
            if (string.IsNullOrWhiteSpace(obj) || !Regex.IsMatch(obj, @"^(\d+([.]\d*)?|[.]\d*)$")) return string.Empty;
            Regex regex = new Regex("^[0]*(?
    ([0-9]+)?)(?([.][0-9]*)?)$");
            MatchEvaluator matchEvaluator = m => string.Concat(m.Groups["pre"].Length > 0 ? m.Groups["pre"].Value : "0", m.Groups["post"].Value.TrimEnd(new[] { '.', '0' }));
            return regex.Replace(obj, matchEvaluator);
        }
    }
    

    Though it will require a reference to System.Numerics.

提交回复
热议问题