
C# round(3 methods, Round(), ToString() and Format())
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.
-
Related Reading
- C# Read and write to text file Newline, with one lin
- C# merge binary array(byte array)
- C# Winform button transparent background with proper
- C# float, double range, precision, definition and ty
- C# efficiency comparison of multiple strings concate
- Bubble sort algorithm example in C# and C (Ascending
- C# Hashtable create, add, update, remove and removed
- C# judge whether cookies are disabled on the client
- C# remove first or last character from string
- C# get url, domain, absolute, relative and physical
- C# if else vs switch, which efficiency is high(multi
- C# label control, with winforms label transparent ba