Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Several ways to round C


May 12, 2021 C#



In daily calculations, numbers after the number after the number of points are often rounded. S o how do you achieve rounding in C#?


If you want to master C more quickly and effectively, we recommend that you take the C-micro-lesson.


1, using the Round() method output

double dValue = 1880.875;
double d = Math.Round(dValue, 2); //输出:1880.88
decimal de = decimal.Round(decimal.Parse(dValue), 2); //输出:1880.88


2, using the ToString() method output

double dValue = 612.576;
string str = dValue.ToString("f2"); //输出:612.58
string str1 = dValue.ToString("#0.00"); //输出:612.58,小数点后有几个0就保留几位


3, the use of Format() method output

double dValue = 201.38769;
string str1 = String.Format("{0:N2}", dValue); //输出:201.39
string str2 = String.Format("{0:N3}", dValue); //输出:201.388
string str3 = String.Format("{0:N4}", dValue); //输出:201.3877


If you need to calculate the accuracy over and over again, theRound() method is recommended to reduce the deviation.