The C #, double, and decimal data types are truncated to retain the specified decimal places.

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.