C # double and decimal data types retain the specified number of decimal places in a truncated way _c# tutorial

Source: Internet
Author: User
Tags pow static class truncated
In the project, you use the truncation method to take two digits after the decimal point, so the following methods are written:
Copy Code code as follows:

<summary>
Truncates a decimal value by the specified number of decimal places
</summary>
<param name= "D" > Decimal number to truncate </param>
<param name= "s" > decimal digits, s greater than or equal to 0, less than or equal to 28</param>
<returns></returns>
public static decimal ToFixed (decimal d, int s)
{
Decimal sp = Convert.todecimal (Math.pow (s));

if (d < 0)
Return Math.truncate (d) + math.ceiling ((d-math.truncate (d)) * sp)/SP;
Else
Return Math.truncate (d) + Math.floor ((d-math.truncate (d)) * sp)/SP;
}

<summary>
Truncates a double-precision floating-point value by the specified number of decimal places
</summary>
<param name= "D" > Double precision floating-point number to truncate </param>
<param name= "s" > decimal digits, s greater than or equal to 0, less than or equal to 15</param>
<returns></returns>
public static double ToFixed (double d, int s)
{
Double sp = Math.pow (s);

if (d < 0)
Return Math.truncate (d) + math.ceiling ((d-math.truncate (d)) * sp)/SP;
Else
Return Math.truncate (d) + Math.floor ((d-math.truncate (d)) * sp)/SP;
}

Incidentally mention:
The ToString ("#.##") method of double and decimal uses rounding;
Static class System.Math under the round (decimal d, int decimals) method, rounding the way used is "four homes six into 50% pairs";
The third parameter of the round (decimal d, int decimals, midpointrounding mode) under Static Class System.Math is an enumeration parameter that indicates how to handle the intermediate value (5);
Static Class System.Math Method: Http://msdn.microsoft.com/zh-cn/library/system.math_methods (v=vs.80)
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.