C # Handling Rounding issues

Source: Internet
Author: User

In dealing with some of the data, we want to be able to use the "rounding" method, but C # uses the "four six into 50% pairs" method, such as the following example, is the "four six into 50% pairs" results obtained:

Double D1 = Math.Round (1.25, 1);//1.2
Double D2 = Math.Round (1.24, 1);//1.2
Double D3 = Math.Round (1.26, 1);//1.3
Double d4 = Math.Round (1.35, 1);//1.4

In order to achieve "rounding" in C #, I wrote the following function:

<summary>
Rounding method of implementing data
</summary>
<param name= "V" > Data to be processed </param>
<param name= "x" > Number of decimal digits reserved </param>
<returns> results after rounding </returns>
Private double Round (double v, int x)
{
BOOL isnegative = false;
If it's a negative number
if (v < 0)
{
Isnegative = true;
v =-V;
}

int ivalue = 1;
for (int i = 1; i <= x; i++)
{
Ivalue = Ivalue * 10;
}
Double Int = Math.Round (v * ivalue + 0.5,0);
v = int/ivalue;

if (isnegative)
{
v =-V;
}

return v;
}

After a simple test, the above function can be rounded up by the data.

C # Handling Rounding issues

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.