.net decimal保留指定的小数位数(不四舍五入)
2019/7/7 18:09:51
本文主要是介绍.net decimal保留指定的小数位数(不四舍五入),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
前言
项目中遇到分摊金额的情况,最后一条的金额=总金额-已经分摊金额的和。
这样可能导致最后一条分摊的时候是负数,所以自己写了一个保留指定位数小数的方法。
扩展方法的使用,使得调用起来很优雅。
示例代码
public static class DecimalExtension { /// <summary> /// decimal保留指定位数小数 /// </summary> /// <param name="num">原始数量</param> /// <param name="scale">保留小数位数</param> /// <returns>截取指定小数位数后的数量字符串</returns> 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(); } } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
这篇关于.net decimal保留指定的小数位数(不四舍五入)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!