码迷,mamicode.com
首页 > Windows程序 > 详细

C# decimal保留指定的小数位数,不四舍五入

时间:2016-12-05 14:08:49      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:style   string   contract   自己   ati   return   form   extension   sub   

decimal保留指定位数小数的时候,.NET自带的方法都是四舍五入的。

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

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

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

技术分享
 1 public static class DecimalExtension
 2     {
 3         /// <summary>
 4         /// decimal保留指定位数小数
 5         /// </summary>
 6         /// <param name="num">原始数量</param>
 7         /// <param name="scale">保留小数位数</param>
 8         /// <returns>截取指定小数位数后的数量字符串</returns>
 9         public static string ToString(this decimal num, int scale)
10         {
11             string numToString = num.ToString();
12 
13             int index = numToString.IndexOf(".");
14             int length = numToString.Length;
15 
16             if (index != -1)
17             {
18                 return string.Format("{0}.{1}",
19                     numToString.Substring(0, index),
20                     numToString.Substring(index + 1, Math.Min(length - index - 1, scale)));
21             }
22             else
23             {
24                 return num.ToString();
25             }
26         }
27     }
decimal保留指定位数小数

 

C# decimal保留指定的小数位数,不四舍五入

标签:style   string   contract   自己   ati   return   form   extension   sub   

原文地址:http://www.cnblogs.com/tanpeng/p/6133523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!