C# rounding to retain two decimals method summary

In development, we often need to round numerical data to keep relevant decimals. I have summarized the three commonly used conversion methods and their corresponding characteristics.

Method 1: Use Math.Round(double,int)
//常规方法:使用Math.Round(),
double num1 = Math.Round(2.455,2);//得到的值是2.46
double num2 = Math.Round(2.445, 2);//得到的值是2.44,实际生活中我们认为应该得到2.45
double num3 = Math.Round(2.454,2);//得到的值是2.45
double num4 = Math.Round(2.456, 2);//得到的值是2.46

The first method is the rounding method that we often use in actual development, but we must pay attention when we use it again . Round() in C# is not rounding as we Chinese understand, it is rounding by foreigners, and it conforms to IEEE standards. Rounding, specifically rounding, if it encounters 5, the previous digit will be rounded off if it is an even number, and if it is an odd number, it will be rounded up .

Method 2: Use Math.Round(double,int,MidpointRounding)
//方法二:使用Math.Round()的重载函数,四舍五入,保留两位数据
double num5 = Math.Round(2.455,2,MidpointRounding.AwayFromZero);//得到的值是2.46
double num6 = Math.Round(2.445,2,MidpointRounding.AwayFromZero);//得到的值是2.45
double num7 = Math.Round(2.454,2,MidpointRounding.AwayFromZero);//得到的值是2.45
double num8 = Math.Round(2.456,2,MidpointRounding.AwayFromZero);//得到的值是2.46

This way is the rounding that we Chinese understand.

Method 3: Use .tostring("0.00") to format
//方式三:使用double.tostring("0.00")进行格式化
double num9 = 2.455;
double num10 = 2.445;
double num11 = 2.456;
double num12 = 2.454;

string strNum9 = num9.ToString("0.00");  //得到的值是"2.46"
string strNum10= num10.ToString("0.00"); //得到的值是"2.45"
string strNum11= num11.ToString("0.00"); //得到的值是"2.46"
string strNum12= num12.ToString("0.00"); //得到的值是"2.45"

Note: If you need to keep 1 decimal place, just use .ToString("0.0"), 3 decimal places and so on

Method 4: Increase 0.*5

If we need to round a number, keep 2 decimal places, and need a value like 2.445 to keep it as 2.45 instead of 2.44, we can also add 0.005 to this number;

//方式三:增加0.005
double num13 = 2.445;
double num14 = 2.455;
double num13To = Math.Round(num13 + 0.005,2);//得到的结果是2.45
double num14To = Math.Round(num14 + 0.005, 2);//得到的结果是2.46

Remarks:
1. If you keep 3 as a decimal, add 0.0005, and so on.
2. This method is also applicable to Convert.ToInt32() for int data conversion.

Summary: A comprehensive comparison of the above four methods shows that the second method is the most applicable and scientific method.

Guess you like

Origin blog.csdn.net/qq_39541254/article/details/107372461