using System; namespace Binance.TradeRobot.Common.Extensions { public static class MathExtension { /// /// 四舍五入保留小数 /// /// /// 保留的位数 /// public static decimal Round(this decimal d, int length) { return Math.Round(d, length, MidpointRounding.AwayFromZero); } /// /// string转换decimal /// /// /// /// public static decimal ToDecimal(this string s, int? length = null) { if (!decimal.TryParse(s, out decimal d)) return 0M; if (length != null) return d.Round(length.Value); return d; } /// /// 截取小数位数,不进行四舍五入 /// /// /// 截取的位数 /// public static decimal CutDecimal(this decimal d, int length) { var dStr = d.ToString(); var dotIndex = dStr.IndexOf("."); var cutLength = dotIndex + 1 + length; if (dotIndex == -1 || dStr.Length <= cutLength) dStr = string.Format($"{{0:F{length}}}", d); else dStr = dStr.Substring(0, cutLength); return decimal.Parse(dStr); } } }