C# round(3 methods, Round(), ToString() and Format())

Lionsure 2020-07-24 Original by the website

It is often necessary to round to decimals in the calculation process. C# provides several methods for it. What are the methods?


1. C# round using Round() method

double dValue = 1880.875;

double d = Math.Round(dValue, 2); //Output: 1880.88, math round c#

decimal de = decimal.Round(decimal.Parse(dValue), 2); //Output: 1880.88


2. C# round using ToString() method

double dValue = 612.576;

string str = dValue.ToString("f2"); //Output: 612.58

string str1 = dValue.ToString("#0.00"); //Output: 612.58, there are a few 0s after the decimal point, just round to a few digits


3. C# round using Format() method

double dValue = 201.38769;

string str1 = String.Format("{0:N2}", dValue); //Output: 201.39

string str2 = String.Format("{0:N3}", dValue); //Output: 201.388

string str3 = String.Format("{0:N4}", dValue); //Output: 201.3877

If you need to repeatedly calculate for the accuracy, it is recommended to use the Round() method, because it can reduce the deviation.