I have been engaged in ASP. NET in C # development for almost a year. Today I know that the truncation method is not used when the number of decimal places is retained in C.
The project uses the truncation method to get the last two digits of the decimal point, so the following method is written:
1 /// <summary>
2 // truncate a small value by the specified number of decimal places
3 /// </summary>
4 /// <param name = "d"> decimals to be truncated </param>
5 // <param name = "s"> number of decimal places, s greater than or equal to 0, less than or equal to 28 </param>
6 /// <returns> </returns>
7 public static decimal ToFixed (decimal d, int s)
8 {
9 decimal sp = Convert. ToDecimal (Math. Pow (10, s ));
10 return Math. Truncate (d) + Math. Floor (d-Math. Truncate (d) * sp)/sp;
11}
12
13 /// <summary>
14 // truncate the double-precision floating point value by the specified decimal point
15 /// </summary>
16 /// <param name = "d"> double-precision floating-point number to be truncated </param>
17 // <param name = "s"> number of decimal places, s greater than or equal to 0, less than or equal to 15 </param>
18 /// <returns> </returns>
19 public static double ToFixed (double d, int s)
20 {
21 double sp = Math. Pow (10, s );
22 return Math. Truncate (d) + Math. Floor (d-Math. Truncate (d) * sp)/sp;
23}
The following is a reference:
1. The double and decimal ToString ("####") methods use rounding;
2. The Round (decimal d, int decimals) method under the static class System. Math. The rounding method uses the "four homes, six homes, five into five pairs ";
3. The third parameter of the Round (decimal d, int decimals, MidpointRounding mode) in the static class System. Math is the enumeration parameter, indicating how to process the median (5 );
Static class System. Math method: http://msdn.microsoft.com/zh-cn/library/system.math_methods (v = vs.80)
Taken from the sword without any marks