程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> C# decimal保留指定的小數位數,不四捨五入,

C# decimal保留指定的小數位數,不四捨五入,

編輯:關於.NET

C# decimal保留指定的小數位數,不四捨五入,


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保留指定位數小數

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved