您现在的位置是:网站首页> 编程资料编程资料

.net decimal保留指定的小数位数(不四舍五入)_实用技巧_

2023-05-24 394人已围观

简介 .net decimal保留指定的小数位数(不四舍五入)_实用技巧_

前言

项目中遇到分摊金额的情况,最后一条的金额=总金额-已经分摊金额的和。

这样可能导致最后一条分摊的时候是负数,所以自己写了一个保留指定位数小数的方法。

扩展方法的使用,使得调用起来很优雅。

示例代码

 public static class DecimalExtension { ///  /// decimal保留指定位数小数 ///  /// 原始数量 /// 保留小数位数 /// 截取指定小数位数后的数量字符串 public static string ToString(this decimal num, int scale) { string numToString = num.ToString(); int index = numToString.IndexOf("."); int length = numToString.Length; if (index != -1) { return string.Format("{0}.{1}", numToString.Substring(0, index), numToString.Substring(index + 1, Math.Min(length - index - 1, scale))); } else { return num.ToString(); } } } 

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

-六神源码网