namespace YLErp.Commons { /// /// 系统格式化选项 /// public class OtcFormatOption { private int _minDecimals; private int _maxDecimals; private string _format; private bool _grouping; private bool _rounded = true; private bool _percent; public OtcFormatOption() { } /// /// 格式化字符串 /// public string GetFormat() { if (_format == null) { _format = NumberHelper.GetFormat(minDecimals: minDecimals, maxDecimals: maxDecimals, percent: percent, grouping: grouping); } return _format; } /// /// 精度(旧字段当前使用minDecimals)(待删除) /// public int precision { get => _minDecimals; set { _format = null; _minDecimals = value < 0 ? 0 : value; } } /// /// 千分位分组(默认false) /// public bool grouping { get => _grouping; set { _format = null; _grouping = value; } } /// /// 是否四舍五入(默认true) /// public bool rounded { get => _rounded; set { _format = null; _rounded = value; } } /// /// 是否百分数(x%)(默认false) /// public virtual bool percent { get => _percent; set { _format = null; _percent = value; } } /// /// 最小小数个数 /// public int minDecimals { get => _minDecimals; set { _format = null; _minDecimals = value < 0 ? 0 : value; } } /// /// 最大小数个数(小于MinDecimals时不起作用) /// public int maxDecimals { get => _maxDecimals; set { _format = null; _maxDecimals = value < 0 ? 0 : value; } } /// /// 非四舍五入情况下 /// public string Format(double d) { if (double.IsNaN(d)) { return string.Empty; } if (!rounded) { d = NumberHelper.Truncate(d, minDecimals: minDecimals, maxDecimals: maxDecimals, percent: percent); } return d.ToString(GetFormat()); } /// /// 非四舍五入情况下 /// public string Format(decimal d) { if (!rounded) { d = NumberHelper.Truncate(d, minDecimals: minDecimals, maxDecimals: maxDecimals, percent: percent); } return d.ToString(GetFormat()); } /// /// /// public double FormatValue(double d) { return OtcFormatHelper.FormatValue(percent ? d * 100 : d, maxDecimals > minDecimals ? maxDecimals : minDecimals, rounded); } /// /// 该方法不可轻易修改,修改需确认 /// 此处用到该逻辑:return FormatModel.trading.premiumRateP < 1 ? "P4" : "P" + FormatModel.trading.premiumRateP; /// public override string ToString() { return $"minDecimals:{minDecimals}-maxDecimals:{maxDecimals}-percent:{percent}-rounded:{rounded}-grouping:{grouping}"; } /// /// 最大精度 /// public int GetMaxPrecision() { return minDecimals < maxDecimals ? maxDecimals : maxDecimals; } public static implicit operator OtcFormatOption(int precision) { return new OtcFormatOption { minDecimals = precision }; } } /// /// 百分比格式的otcformat /// public class OtcFormatOptionPercent : OtcFormatOption { public override bool percent => true; public OtcFormatOption ToNonPercentOption() { return new OtcFormatOption { rounded = rounded, grouping = grouping, minDecimals = minDecimals + 2, maxDecimals = maxDecimals + 2, percent = false }; } public static implicit operator OtcFormatOptionPercent(int precision) { return new OtcFormatOptionPercent { minDecimals = precision }; } } }