Is there a display formatter that will output decimals as these string representations in c# without doing any rounding?
// decimal -> string
20 -> 20
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.