C # decimal retains the specified decimal places,
When decimal retains the specified decimal digits, the. NET method is rounding.
If the project encounters a apportioned amount, the amount in the last line = total amount-sum of the apportioned amount.
This may result in a negative number when the last part is apportioned. Therefore, I wrote a method to retain the decimal digits of the specified number.
The use of extension methods makes calling very elegant.
1 public static class DecimalExtension 2 {3 /// <summary> 4 /// decimal keep the specified number of digits 5 /// </summary> 6 /// <param name =" num "> original quantity </param> 7 // <param name =" scale "> retain decimal places </param> 8 /// <returns> after the specified decimal places are intercepted number of strings </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 else23 {24 return num. toString (); 25} 26} 27}
Decimal reserved decimal digits