您现在的位置是:网站首页> 编程资料编程资料
.net decimal保留指定的小数位数(不四舍五入)_实用技巧_
2023-05-24
397人已围观
简介 .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(); } } } 总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
您可能感兴趣的文章:
相关内容
- 详解ASP.NET MVC的筛选器_实用技巧_
- [Asp.Net MVC4]验证用户登录实现实例_实用技巧_
- ASP.NET SignaiR 实现消息的即时推送,并使用Push.js实现通知的示例代码_实用技巧_
- 解析Asp.net Core中使用Session的方法_实用技巧_
- 详解mvc使用JsonResult返回Json数据_实用技巧_
- VS2015使用scanf报错的解决方法_实用技巧_
- .NET获取当前路径的方法汇总_实用技巧_
- asp.net core mvc实现文件上传实例_实用技巧_
- asp.net mvc验证码类使用_实用技巧_
- asp.net webform自定义分页控件_实用技巧_
